Kotlin + Netty 在 Android 上實現 Socket 的服務端

Tony沈哲發表於2019-08-11

一. 背景

最近的一個專案:需要使用 Android App 作為 Socket 的服務端,並且一個埠能夠同時監聽 TCP/Web Socket 協議。

自然而然,專案決定採用 Netty 框架。Netty 服務端在收到客戶端發來的訊息後,能夠做出相應的業務處理。在某些場景下,服務端也需要給客戶端 App/網頁傳送訊息。

二. Netty 的使用

2.1 Netty 服務端

首先,定義好 NettyServer,它使用object宣告表示是一個單例。用於 Netty 服務端的啟動、關閉以及傳送訊息。

object NettyServer {

    private val TAG = "NettyServer"

    private var channel: Channel?=null
    private lateinit var listener: NettyServerListener<String>
    private lateinit var bossGroup: EventLoopGroup
    private lateinit var workerGroup: EventLoopGroup

    var port = 8888
        set(value)  {
            field = value
        }

    var webSocketPath = "/ws"
        set(value)  {
            field = value
        }

    var isServerStart: Boolean = false
        private set

    fun start() {
        object : Thread() {
            override fun run() {
                super.run()
                bossGroup = NioEventLoopGroup(1)
                workerGroup = NioEventLoopGroup()
                try {
                    val b = ServerBootstrap()
                    b.group(bossGroup, workerGroup)
                            .channel(NioServerSocketChannel::class.java)
                            .localAddress(InetSocketAddress(port))
                            .childOption(ChannelOption.SO_KEEPALIVE, true)
                            .childOption(ChannelOption.SO_REUSEADDR, true)
                            .childOption(ChannelOption.TCP_NODELAY, true)
                            .childHandler(NettyServerInitializer(listener,webSocketPath))

                    // Bind and start to accept incoming connections.
                    val f = b.bind().sync()
                    Log.i(TAG, NettyServer::class.java.name + " started and listen on " + f.channel().localAddress())

                    isServerStart = true
                    listener.onStartServer()
                    f.channel().closeFuture().sync()
                } catch (e: Exception) {
                    Log.e(TAG, e.localizedMessage)
                    e.printStackTrace()
                } finally {
                    isServerStart = false
                    listener.onStopServer()

                    disconnect()
                }
            }
        }.start()

    }

    fun disconnect() {
        workerGroup.shutdownGracefully()
        bossGroup.shutdownGracefully()
    }

    fun setListener(listener: NettyServerListener<String>) {
        this.listener = listener
    }

    // 非同步傳送TCP訊息
    fun sendMsgToClient(data: String, listener: ChannelFutureListener) = channel?.run {

        val flag = this.isActive

        if (flag) {

            this.writeAndFlush(data + System.getProperty("line.separator")).addListener(listener)
        }

        flag
    } ?: false

    // 同步傳送TCP訊息
    fun sendMsgToClient(data: String) = channel?.run {

        if (this.isActive) {

            return this.writeAndFlush(data + System.getProperty("line.separator")).awaitUninterruptibly().isSuccess
        }

        false
    } ?: false

    // 非同步傳送WebSocket訊息
    fun sendMsgToWS(data: String,listener: ChannelFutureListener) = channel?.run {

        val flag = this.isActive

        if (flag) {

            this.writeAndFlush(TextWebSocketFrame(data)).addListener(listener)
        }

        flag
    } ?: false

    // 同步傳送TCP訊息
    fun sendMsgToWS(data: String) = channel?.run {

        if (this.isActive) {

            return this.writeAndFlush(TextWebSocketFrame(data)).awaitUninterruptibly().isSuccess
        }

        false
    } ?: false

    /**
     * 切換通道
     * 設定服務端,與哪個客戶端通訊
     * @param channel
     */
    fun selectorChannel(channel: Channel?) {
        this.channel = channel
    }
}
複製程式碼

NettyServerInitializer 是服務端跟客戶端連線之後使用的 childHandler:

class NettyServerInitializer(private val mListener: NettyServerListener<String>,private val webSocketPath:String) : ChannelInitializer<SocketChannel>() {

    @Throws(Exception::class)
    public override fun initChannel(ch: SocketChannel) {

        val pipeline = ch.pipeline()

        pipeline.addLast("active",ChannelActiveHandler(mListener))
        pipeline.addLast("socketChoose", SocketChooseHandler(webSocketPath))

        pipeline.addLast("string_encoder",StringEncoder(CharsetUtil.UTF_8))
        pipeline.addLast("linebased",LineBasedFrameDecoder(1024))
        pipeline.addLast("string_decoder",StringDecoder(CharsetUtil.UTF_8))
        pipeline.addLast("commonhandler", CustomerServerHandler(mListener))
    }
}
複製程式碼

NettyServerInitializer 包含了多個 Handler:連線使用的ChannelActiveHandler,協議選擇使用的 SocketChooseHandler,TCP 訊息使用的 StringEncoder、LineBasedFrameDecoder、StringDecoder,以及最終處理訊息的 CustomerServerHandler。

ChannelActiveHandler:

@ChannelHandler.Sharable
class ChannelActiveHandler(var mListener: NettyServerListener<String>) : ChannelInboundHandlerAdapter() {

    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {

        val insocket = ctx.channel().remoteAddress() as InetSocketAddress
        val clientIP = insocket.address.hostAddress
        val clientPort = insocket.port

        Log.i("ChannelActiveHandler","新的連線:$clientIP : $clientPort")
        mListener.onChannelConnect(ctx.channel())
    }

}
複製程式碼

SocketChooseHandler 通過讀取訊息來區分是 WebSocket 還是 Socket。如果是 WebSocket 的話,去掉 Socket 使用的相關 Handler。

class SocketChooseHandler(val webSocketPath:String) : ByteToMessageDecoder() {

    @Throws(Exception::class)
    override fun decode(ctx: ChannelHandlerContext, `in`: ByteBuf, out: List<Any>) {
        val protocol = getBufStart(`in`)
        if (protocol.startsWith(WEBSOCKET_PREFIX)) {
            PipelineAdd.websocketAdd(ctx,webSocketPath)

            ctx.pipeline().remove("string_encoder")
            ctx.pipeline().remove("linebased")
            ctx.pipeline().remove("string_decoder")
        }
        `in`.resetReaderIndex()
        ctx.pipeline().remove(this.javaClass)
    }

    private fun getBufStart(`in`: ByteBuf): String {
        var length = `in`.readableBytes()
        if (length > MAX_LENGTH) {
            length = MAX_LENGTH
        }

        // 標記讀位置
        `in`.markReaderIndex()
        val content = ByteArray(length)
        `in`.readBytes(content)
        return String(content)
    }

    companion object {
        /** 預設暗號長度為23  */
        private val MAX_LENGTH = 23
        /** WebSocket握手的協議字首  */
        private val WEBSOCKET_PREFIX = "GET /"
    }
}
複製程式碼

StringEncoder、LineBasedFrameDecoder、StringDecoder 都是 Netty 內建的編、解碼器。其中,LineBasedFrameDecoder 用於解決 TCP粘包/拆包的問題。

CustomerServerHandler:

@ChannelHandler.Sharable
class CustomerServerHandler(private val mListener: NettyServerListener<String>) : SimpleChannelInboundHandler<Any>() {

    @Throws(Exception::class)
    override fun channelReadComplete(ctx: ChannelHandlerContext) {
    }

    override fun exceptionCaught(ctx: ChannelHandlerContext,
                                 cause: Throwable) {
        cause.printStackTrace()
        ctx.close()
    }

    @Throws(Exception::class)
    override fun channelRead0(ctx: ChannelHandlerContext, msg: Any) {

        val buff = msg as ByteBuf
        val info = buff.toString(CharsetUtil.UTF_8)
        Log.d(TAG,"收到訊息內容:$info")
    }

    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {

        if (msg is WebSocketFrame) {  // 處理 WebSocket 訊息

            val webSocketInfo = (msg as TextWebSocketFrame).text().trim { it <= ' ' }

            Log.d(TAG, "收到WebSocketSocket訊息:$webSocketInfo")

            mListener.onMessageResponseServer(webSocketInfo , ctx.channel().id().asShortText())
        } else if (msg is String){   // 處理 Socket 訊息

            Log.d(TAG, "收到socket訊息:$msg")

            mListener.onMessageResponseServer(msg, ctx.channel().id().asShortText())
        }
    }

    // 斷開連線
    @Throws(Exception::class)
    override fun channelInactive(ctx: ChannelHandlerContext) {
        super.channelInactive(ctx)
        Log.d(TAG, "channelInactive")

        val reAddr = ctx.channel().remoteAddress() as InetSocketAddress
        val clientIP = reAddr.address.hostAddress
        val clientPort = reAddr.port

        Log.d(TAG,"連線斷開:$clientIP : $clientPort")

        mListener.onChannelDisConnect(ctx.channel())
    }

    companion object {

        private val TAG = "CustomerServerHandler"
    }
}
複製程式碼

2.2 Netty 客戶端

客戶端也需要一個啟動、關閉、傳送訊息的 NettyTcpClient,並且 NettyTcpClient 的建立採用 Builder 模式。

class NettyTcpClient private constructor(val host: String, val tcp_port: Int, val index: Int) {

    private lateinit var group: EventLoopGroup

    private lateinit var listener: NettyClientListener<String>

    private var channel: Channel? = null

    /**
     * 獲取TCP連線狀態
     *
     * @return  獲取TCP連線狀態
     */
    var connectStatus = false

    /**
     * 最大重連次數
     */
    var maxConnectTimes = Integer.MAX_VALUE
        private set

    private var reconnectNum = maxConnectTimes

    private var isNeedReconnect = true

    var isConnecting = false
        private set

    var reconnectIntervalTime: Long = 5000
        private set

    /**
     * 心跳間隔時間
     */
    var heartBeatInterval: Long = 5
        private set//單位秒

    /**
     * 是否傳送心跳
     */
    var isSendheartBeat = false
        private set

    /**
     * 心跳資料,可以是String型別,也可以是byte[].
     */
    private var heartBeatData: Any? = null

    fun connect() {
        if (isConnecting) {
            return
        }

        val clientThread = object : Thread("Netty-Client") {
            override fun run() {
                super.run()
                isNeedReconnect = true
                reconnectNum = maxConnectTimes
                connectServer()
            }
        }
        clientThread.start()
    }


    private fun connectServer() {

        synchronized(this@NettyTcpClient) {

            var channelFuture: ChannelFuture?=null

            if (!connectStatus) {
                isConnecting = true
                group = NioEventLoopGroup()
                val bootstrap = Bootstrap().group(group)
                        .option(ChannelOption.TCP_NODELAY, true)//遮蔽Nagle演算法試圖
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                        .channel(NioSocketChannel::class.java as Class<out Channel>?)
                        .handler(object : ChannelInitializer<SocketChannel>() {

                            @Throws(Exception::class)
                            public override fun initChannel(ch: SocketChannel) {

                                if (isSendheartBeat) {
                                    ch.pipeline().addLast("ping", IdleStateHandler(0, heartBeatInterval, 0, TimeUnit.SECONDS)) //5s未傳送資料,回撥userEventTriggered
                                }

                                ch.pipeline().addLast(StringEncoder(CharsetUtil.UTF_8))
                                ch.pipeline().addLast(StringDecoder(CharsetUtil.UTF_8))
                                ch.pipeline().addLast(LineBasedFrameDecoder(1024))//黏包處理,需要客戶端、服務端配合
                                ch.pipeline().addLast(NettyClientHandler(listener, index, isSendheartBeat, heartBeatData))
                            }
                        })

                try {
                    channelFuture = bootstrap.connect(host, tcp_port).addListener {
                        if (it.isSuccess) {
                            Log.d(TAG, "連線成功")
                            reconnectNum = maxConnectTimes
                            connectStatus = true
                            channel = channelFuture?.channel()
                        } else {
                            Log.d(TAG, "連線失敗")
                            connectStatus = false
                        }
                        isConnecting = false
                    }.sync()

                    // Wait until the connection is closed.
                    channelFuture.channel().closeFuture().sync()
                    Log.d(TAG, " 斷開連線")
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    connectStatus = false
                    listener.onClientStatusConnectChanged(ConnectState.STATUS_CONNECT_CLOSED, index)

                    if (channelFuture != null) {
                        if (channelFuture.channel() != null && channelFuture.channel().isOpen) {
                            channelFuture.channel().close()
                        }
                    }
                    group.shutdownGracefully()
                    reconnect()
                }
            }
        }
    }


    fun disconnect() {
        Log.d(TAG, "disconnect")
        isNeedReconnect = false
        group.shutdownGracefully()
    }

    fun reconnect() {
        Log.d(TAG, "reconnect")
        if (isNeedReconnect && reconnectNum > 0 && !connectStatus) {
            reconnectNum--
            SystemClock.sleep(reconnectIntervalTime)
            if (isNeedReconnect && reconnectNum > 0 && !connectStatus) {
                Log.e(TAG, "重新連線")
                connectServer()
            }
        }
    }

    /**
     * 非同步傳送
     *
     * @param data 要傳送的資料
     * @param listener 傳送結果回撥
     * @return 方法執行結果
     */
    fun sendMsgToServer(data: String, listener: MessageStateListener) = channel?.run {

        val flag = this != null && connectStatus

        if (flag) {

            this.writeAndFlush(data + System.getProperty("line.separator")).addListener { channelFuture -> listener.isSendSuccss(channelFuture.isSuccess) }
        }

        flag

    } ?: false

    /**
     * 同步傳送
     *
     * @param data 要傳送的資料
     * @return 方法執行結果
     */
    fun sendMsgToServer(data: String) = channel?.run {

        val flag = this != null && connectStatus

        if (flag) {

            val channelFuture = this.writeAndFlush(data + System.getProperty("line.separator")).awaitUninterruptibly()
            return channelFuture.isSuccess
        }

        false

    }?:false

    fun setListener(listener: NettyClientListener<String>) {
        this.listener = listener
    }

    /**
     * Builder 模式建立NettyTcpClient
     */
    class Builder {

        /**
         * 最大重連次數
         */
        private var MAX_CONNECT_TIMES = Integer.MAX_VALUE

        /**
         * 重連間隔
         */
        private var reconnectIntervalTime: Long = 5000
        /**
         * 伺服器地址
         */
        private var host: String? = null
        /**
         * 伺服器埠
         */
        private var tcp_port: Int = 0
        /**
         * 客戶端標識,(因為可能存在多個連線)
         */
        private var mIndex: Int = 0

        /**
         * 是否傳送心跳
         */
        private var isSendheartBeat: Boolean = false
        /**
         * 心跳時間間隔
         */
        private var heartBeatInterval: Long = 5

        /**
         * 心跳資料,可以是String型別,也可以是byte[].
         */
        private var heartBeatData: Any? = null


        fun setMaxReconnectTimes(reConnectTimes: Int): Builder {
            this.MAX_CONNECT_TIMES = reConnectTimes
            return this
        }


        fun setReconnectIntervalTime(reconnectIntervalTime: Long): Builder {
            this.reconnectIntervalTime = reconnectIntervalTime
            return this
        }


        fun setHost(host: String): Builder {
            this.host = host
            return this
        }

        fun setTcpPort(tcp_port: Int): Builder {
            this.tcp_port = tcp_port
            return this
        }

        fun setIndex(mIndex: Int): Builder {
            this.mIndex = mIndex
            return this
        }

        fun setHeartBeatInterval(intervalTime: Long): Builder {
            this.heartBeatInterval = intervalTime
            return this
        }

        fun setSendheartBeat(isSendheartBeat: Boolean): Builder {
            this.isSendheartBeat = isSendheartBeat
            return this
        }

        fun setHeartBeatData(heartBeatData: Any): Builder {
            this.heartBeatData = heartBeatData
            return this
        }

        fun build(): NettyTcpClient {
            val nettyTcpClient = NettyTcpClient(host!!, tcp_port, mIndex)
            nettyTcpClient.maxConnectTimes = this.MAX_CONNECT_TIMES
            nettyTcpClient.reconnectIntervalTime = this.reconnectIntervalTime
            nettyTcpClient.heartBeatInterval = this.heartBeatInterval
            nettyTcpClient.isSendheartBeat = this.isSendheartBeat
            nettyTcpClient.heartBeatData = this.heartBeatData
            return nettyTcpClient
        }
    }

    companion object {
        private val TAG = "NettyTcpClient"
        private val CONNECT_TIMEOUT_MILLIS = 5000
    }
}
複製程式碼

Android 的客戶端相對而言比較簡單,需要的 Handler 包括:支援心跳的 IdleStateHandler, TCP 訊息需要使用的 Handler (跟服務端一樣分別是StringEncoder、StringDecoder、LineBasedFrameDecoder),以及對收到 TCP 訊息進行處理的 NettyClientHandler。

NettyClientHandler:

class NettyClientHandler(private val listener: NettyClientListener<String>, private val index: Int, private val isSendheartBeat: Boolean, private val heartBeatData: Any?) : SimpleChannelInboundHandler<String>() {

    /**
     *
     * 設定IdleStateHandler心跳檢測每x秒進行一次讀檢測,
     * 如果x秒內ChannelRead()方法未被呼叫則觸發一次userEventTrigger()方法
     *
     * @param ctx ChannelHandlerContext
     * @param evt IdleStateEvent
     */
    override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {

        if (evt is IdleStateEvent) {
            if (evt.state() == IdleState.WRITER_IDLE) {   //傳送心跳

                if (isSendheartBeat) {
                    if (heartBeatData == null) {

                        ctx.channel().writeAndFlush("Heartbeat" + System.getProperty("line.separator")!!)
                    } else {

                        if (heartBeatData is String) {
                            Log.d(TAG, "userEventTriggered: String")
                            ctx.channel().writeAndFlush(heartBeatData + System.getProperty("line.separator")!!)
                        } else if (heartBeatData is ByteArray) {
                            Log.d(TAG, "userEventTriggered: byte")
                            val buf = Unpooled.copiedBuffer((heartBeatData as ByteArray?)!!)
                            ctx.channel().writeAndFlush(buf)
                        } else {

                            Log.d(TAG, "userEventTriggered: heartBeatData type error")
                        }
                    }
                } else {
                    Log.d(TAG, "不傳送心跳")
                }
            }
        }
    }

    /**
     *
     * 客戶端上線
     *
     * @param ctx ChannelHandlerContext
     */
    override fun channelActive(ctx: ChannelHandlerContext) {

        Log.d(TAG, "channelActive")
        listener.onClientStatusConnectChanged(ConnectState.STATUS_CONNECT_SUCCESS, index)
    }

    /**
     *
     * 客戶端下線
     *
     * @param ctx ChannelHandlerContext
     */
    override fun channelInactive(ctx: ChannelHandlerContext) {

        Log.d(TAG, "channelInactive")
    }

    /**
     * 客戶端收到訊息
     *
     * @param channelHandlerContext ChannelHandlerContext
     * @param msg                   訊息
     */
    override fun channelRead0(channelHandlerContext: ChannelHandlerContext, msg: String) {

        Log.d(TAG, "channelRead0:")
        listener.onMessageResponseClient(msg, index)
    }

    /**
     * @param ctx   ChannelHandlerContext
     * @param cause 異常
     */
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {

        Log.e(TAG, "exceptionCaught")
        listener.onClientStatusConnectChanged(ConnectState.STATUS_CONNECT_ERROR, index)
        cause.printStackTrace()
        ctx.close()
    }

    companion object {

        private val TAG = "NettyClientHandler"
    }
}
複製程式碼

三. Demo 的實現

3.1 Socket 服務端

啟動 NettyServer:

    private fun startServer() {

        if (!NettyServer.isServerStart) {
            NettyServer.setListener(this@MainActivity)
            NettyServer.port = port
            NettyServer.webSocketPath = webSocketPath
            NettyServer.start()
        } else {
            NettyServer.disconnect()
        }
    }
複製程式碼

NettyServer 非同步傳送 TCP 訊息:

NettyServer.sendMsgToClient(msg, ChannelFutureListener { channelFuture ->

        if (channelFuture.isSuccess) {

            msgSend(msg)
      } 
})
複製程式碼

NettyServer 非同步傳送 WebSocket 訊息:

NettyServer.sendMsgToWS(msg, ChannelFutureListener { channelFuture ->

        if (channelFuture.isSuccess) {

              msgSend(msg)
      } 
 })
複製程式碼

Demo 可以通過 startServer 來啟動 Socket 服務端,也可以在啟動之前點選 configServer 來修改服務端的埠以及 WebSocket 的 Endpoint。

NettyServer1.png

3.2 Socket 客戶端

NettyTcpClient 通過 Builder 模式建立:

            mNettyTcpClient = NettyTcpClient.Builder()
                    .setHost(ip)                    //設定服務端地址
                    .setTcpPort(port)               //設定服務端埠號
                    .setMaxReconnectTimes(5)        //設定最大重連次數
                    .setReconnectIntervalTime(5)    //設定重連間隔時間。單位:秒
                    .setSendheartBeat(false)        //設定傳送心跳
                    .setHeartBeatInterval(5)        //設定心跳間隔時間。單位:秒
                    .setHeartBeatData("I'm is HeartBeatData") //設定心跳資料,可以是String型別,也可以是byte[],以後設定的為準
                    .setIndex(0)                    //設定客戶端標識.(因為可能存在多個tcp連線)
                    .build()

            mNettyTcpClient.setListener(this@MainActivity) //設定TCP監聽
複製程式碼

啟動、關閉客戶端連線:

    private fun connect() {
        Log.d(TAG, "connect")
        if (!mNettyTcpClient.connectStatus) {
            mNettyTcpClient.connect()//連線伺服器
        } else {
            mNettyTcpClient.disconnect()
        }
    }
複製程式碼

NettyTcpClient 非同步傳送 TCP 訊息到服務端:

mNettyTcpClient.sendMsgToServer(msg, object : MessageStateListener {
         override fun isSendSuccss(isSuccess: Boolean) {
                if (isSuccess) {
                           
                   msgSend(msg)
               } 
         }
})
複製程式碼

Demo 的客戶端 App 也可以在啟動之前點選 configClient 來修改要連線的服務端 IP 、埠。

NettyTcpClientpng.png

NettyServer2.png

WebSocket 的測試可以通過:www.websocket-test.com/

Netty Server 端跟網頁通訊:

NettyServer3.png

WebSocket線上測試:

websocket_test.png

四. 總結

藉助 Kotlin 的特性以及 Netty 框架,我們在 Android 上也實現了一個 Socket 服務端。

本文 demo github 地址:github.com/fengzhizi71…

本文的例子很簡單,只是傳送簡單的訊息。在實際生產環境中,我們採用的訊息格式可能是 json ,因為 json 更加靈活,通過解析 json 獲取訊息的內容。

參考資料:

  1. github.com/aLittleGree…
  2. Netty 實現 一個埠同時接收 socket 和 webSocket 連線

Java與Android技術棧:每週更新推送原創技術文章,歡迎掃描下方的公眾號二維碼並關注,期待與您的共同成長和進步。

Kotlin + Netty 在 Android 上實現 Socket 的服務端

相關文章