Android kotlin使用Netty网络框架实践(客户端、服务端)

2024-09-03 08:28

本文主要是介绍Android kotlin使用Netty网络框架实践(客户端、服务端),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开发工具:Android studio 

语言:kotlin

设计原理:通讯协议:头+类型+长度+数据+尾,自定义编解码器,解析和包装发送数据流,以下贴出部分关键代码

说明:代码中封装了client和server端,可以点击按钮进行通讯,可以直接在项目中使用,尤其是处理了粘包和分包问题。

编译后的效果图:

注:结尾附上完整代码下载链接

1、配置build.gradle文件

 implementation("io.netty:netty-all:5.0.0.Alpha2")

2、主要代码

2.1 server端主要代码
    /*** 启动服务端*/fun start() {Executors.newSingleThreadScheduledExecutor().submit {XLogUtil.d( "********服务启动********")bossGroup =NioEventLoopGroup()workerGroup = NioEventLoopGroup()try {val channelInit = ChannelInitServer(serverManager)val serverBootstrap = ServerBootstrap()serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel::class.java)//线程组设置为非阻塞.childHandler(channelInit).option(ChannelOption.SO_BACKLOG, 128)//连接缓冲池的大小.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false)//设置长连接channelFuture = serverBootstrap.bind(Constant.SERVICE_POSR)channel = channelFuture?.channel()channelFuture!!.addListener { future: Future<in Void> ->if (future.isSuccess) {//服务启动成功XLogUtil.d("********服务启动成功********")MessageHandler.sendMessage(MessageType.SERVER_START_SUCCESS,"服务启动成功")} else {//服务启动失败XLogUtil.e("********服务启动失败********")MessageHandler.sendMessage(MessageType.SERVER_START_FAILED,"服务启动失败")}}} catch (e: Exception) {e.printStackTrace()XLogUtil.e( "NettyServer 服务异常:"+e.message)} finally {}}}
2.2 client端主要代码
    /*** 启动客户端*/fun start() {Executors.newSingleThreadScheduledExecutor().submit {XLogUtil.d("***********启动客户端***********")val group: EventLoopGroup = NioEventLoopGroup()try {val channelInit = ChannelInitClient(clientManager)val bootstrap = Bootstrap()bootstrap.group(group).channel(NioSocketChannel::class.java).remoteAddress(InetSocketAddress(address, port)).handler(channelInit).option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, false)val channelFuture = bootstrap.connect().sync()channel = channelFuture.channel()channelFuture!!.addListener { future: Future<in Void> ->if (future.isSuccess) {//绑定成功XLogUtil.d("***********客户端连接成功***********")MessageHandler.sendMessage(MessageType.CLIENT_CONNECT_SUCCESS,"客户端连接成功")} else {//绑定失败XLogUtil.d("***********客户端连接失败***********")MessageHandler.sendMessage(MessageType.CLIENT_CONNECT_FAILED,"客户端连接失败")}}channel!!.closeFuture().sync()XLogUtil.d("***********客户端关闭成功***********")MessageHandler.sendMessage(MessageType.CLIENT_CLOSE_SUCCESS,"客户端关闭成功")} catch (e: Exception) {e.printStackTrace()MessageHandler.sendMessage(MessageType.CLIENT_EXCEPTION,"客户端异常:" + e.message)XLogUtil.e("NettyClient 客户端异常:" + e.message)} finally {try {group.shutdownGracefully().sync()} catch (e: InterruptedException) {e.printStackTrace()MessageHandler.sendMessage(MessageType.CLIENT_EXCEPTION,"客户端异常2:" + e.message)XLogUtil.e("NettyClient 客户端异常2:" + e.message)}}}}
 2.3 Server端线程
ChannelInitServer.kt
服务端数据收发线程
class ChannelInitServer internal constructor(adapter: MyServerHandler) :ChannelInitializer<SocketChannel?>() {private val adapter: MyServerHandlerinit {this.adapter = adapter}override fun initChannel(ch: SocketChannel?) {try {val channelPipeline: ChannelPipeline = ch!!.pipeline()//添加心跳机制,例:每3000ms发送一次心跳//channelPipeline.addLast(IdleStateHandler(3000, 3000, 3000, TimeUnit.MILLISECONDS))//添加数据处理(接收、发送、心跳)//FrameCodec 中处理粘包分包问题channelPipeline.addLast(FrameCodec())channelPipeline.addLast(adapter)} catch (e: Exception) {e.printStackTrace()}}
}
2.4 client 端线程
客户端数据收发线程
class ChannelInitClient internal constructor(adapter: MyClientHandler) :ChannelInitializer<Channel?>() {private val adapter: MyClientHandlerinit {this.adapter = adapter}override fun initChannel(ch: Channel?) {try {if (ch == null) {XLogUtil.e("ChannelInitClient Channel==null,initChannel fail")}val channelPipeline: ChannelPipeline = ch!!.pipeline()//添加心跳机制,例:每3000ms发送一次心跳// channelPipeline.addLast(IdleStateHandler(3000, 3000, 3000, TimeUnit.MILLISECONDS))//自定义编解码器,处理粘包分包问题channelPipeline.addLast(FrameCodec())//添加数据处理channelPipeline.addLast(adapter)} catch (e: Exception) {e.printStackTrace()}}
}
2.5 在Activity文件中调用
package com.android.agentimport android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.fastjson.JSON
import com.android.agent.netty.NettyClient
import com.android.agent.netty.NettyServer
import com.android.agent.netty.message.MessageSend
import com.android.agent.netty.message.SettingIp
import com.android.agent.utils.Constant
import com.android.agent.xlog.XLogUtil
import com.android.agent.Rclass MainActivity : AppCompatActivity() {private var isTestServer = falseprivate var isTestClient = falseprivate var client: NettyClient? = nullprivate var server: NettyServer? = nullprivate var result = ""private var tvResult: TextView? = null@SuppressLint("MissingInflatedId")override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {if (!Environment.isExternalStorageManager()) {val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);startActivity(intent);return;}}XLogUtil.d(">>>>>>>>>>welcome to  AndroidGif")tvResult = findViewById<TextView>(R.id.tv_text)findViewById<Button>(R.id.btnTestClient).setOnClickListener {XLogUtil.d(">>>>>>>>>>btnTestClient OnClick 启动"+!isTestClient)if (!isTestClient) {result = "";testNettyClient();} else {stopNettyClient();}isTestClient = !isTestClient;}findViewById<Button>(R.id.btnTestServer).setOnClickListener {XLogUtil.d(">>>>>>>>>>btnTestServer OnClicks 启动:"+!isTestServer)if (!isTestServer) {result = "";testNettyServer();} else {stopNettyServer();}isTestServer = !isTestServer;}findViewById<Button>(R.id.btnClientSend).setOnClickListener {client?.apply {XLogUtil.d("btnClientSend data")var setIp= SettingIp("192.168.11.185","192.168.11.1","255.255.255.0","8.8.8.8")var sendMsg= MessageSend("xxxxxxxxxxxx",3000,JSON.toJSONString(setIp))sentData(JSON.toJSONString(sendMsg),0x30) //charset("GBK")}}}private fun testNettyClient() {client = NettyClient(Constant.SERVICE_IP, Constant.SERVICE_POSR)
//        client.addHeartBeat(object : HeartBeatListener {
//            override fun getHeartBeat(): ByteArray {
//                val data = "心跳"
//                try {
//                    client.sentData("测试数据".toByteArray(charset("GBK")))
//                    return data.toByteArray(charset("GBK"))
//                } catch (e: UnsupportedEncodingException) {
//                    e.printStackTrace()
//                }
//                return "".toByteArray()
//            }
//        })client!!.setHandler(handler)client!!.start()}private fun stopNettyClient() {client?.apply {stop()}}private fun testNettyServer() {server = NettyServer.getInstance()server?.apply {
//            addHeartBeat(object : HeartBeatListener {
//                override fun getHeartBeat(): ByteArray {
//                    val data = "心跳"
//                    try {
//                        sentData("123".toByteArray(Charsets.UTF_8))//GBK
//                        return data.toByteArray(Charsets.UTF_8)
//                    } catch (e: UnsupportedEncodingException) {
//                        e.printStackTrace()
//                    }
//                    return "".toByteArray()
//                }
//            })setHandler(handler)start()}}private fun stopNettyServer() {server?.apply {stop()}}@SuppressLint("HandlerLeak")private val handler: Handler = object : Handler() {override fun handleMessage(msg: Message) {XLogUtil.d("收到信息:::" + msg.obj.toString())result += "\r\n"result += msg.objtvResult!!.text = "收到信息:$result"}}}

对应的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.android.agent.MainActivity"><Buttonandroid:id="@+id/btnTestServer"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="测试服务端"android:layout_gravity="center_horizontal"android:layout_marginTop="50dp"/><Buttonandroid:id="@+id/btnTestClient"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:layout_marginTop="100dp"android:text="测试客户端"/><Buttonandroid:id="@+id/btnClientSend"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:layout_marginTop="100dp"android:text="客户端发送数据"/><TextViewandroid:id="@+id/tv_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:layout_marginTop="100dp"android:text="收到信息:"/></LinearLayout>
2.6 数据编码解码器

需要根据协议去定义自己的编解码器,处理粘包丢包问题

完整代码下载地址:https://download.csdn.net/download/banzhuantuqiang/89705769

这篇关于Android kotlin使用Netty网络框架实践(客户端、服务端)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1132510

相关文章

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND

C# $字符串插值的使用

《C#$字符串插值的使用》本文介绍了C#中的字符串插值功能,详细介绍了使用$符号的实现方式,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录$ 字符使用方式创建内插字符串包含不同的数据类型控制内插表达式的格式控制内插表达式的对齐方式内插表达式中使用转义序列内插表达式中使用

flask库中sessions.py的使用小结

《flask库中sessions.py的使用小结》在Flask中Session是一种用于在不同请求之间存储用户数据的机制,Session默认是基于客户端Cookie的,但数据会经过加密签名,防止篡改,... 目录1. Flask Session 的基本使用(1) 启用 Session(2) 存储和读取 Se

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

Linux系统之lvcreate命令使用解读

《Linux系统之lvcreate命令使用解读》lvcreate是LVM中创建逻辑卷的核心命令,支持线性、条带化、RAID、镜像、快照、瘦池和缓存池等多种类型,实现灵活存储资源管理,需注意空间分配、R... 目录lvcreate命令详解一、命令概述二、语法格式三、核心功能四、选项详解五、使用示例1. 创建逻