您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    基于 Kotlin 完成一个复杂的 TCP 自定义协议(3)
    时间:2020-09-18 12:05 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

                    override fun initChannel(nioSocketChannel: NioSocketChannel) { 

                        val pipeline = nioSocketChannel.pipeline() 

                        pipeline.addLast(ServerIdleHandler())                        pipeline.addLast(MagicNumValidator())                        pipeline.addLast(PacketCodecHandler)                        pipeline.addLast(HeartBeatHandler)                        pipeline.addLast(ResponseHandler)                    }                })        val future: ChannelFuture = bootstrap.bind(TCP_PORT) 

        future.addListener(object : ChannelFutureListener { 

            @Throws(Exception::class) 

            override fun operationComplete(channelFuture: ChannelFuture) { 

                if (channelFuture.isSuccess) { 

                    logInfo(logger, "TCP Server is starting..."

                } else { 

                    logError(logger,channelFuture.cause(),"TCP Server failed"

                }            }        })    } 

    其中,ServerIdleHandler: 表示 5 分钟内没有收到心跳,则断开衔接。

    class ServerIdleHandler : IdleStateHandler(0, 0, HERT_BEAT_TIME) { 

        private val logger: Logger = LoggerFactory.getLogger(ServerIdleHandler::class.java) 

        @Throws(Exception::class) 

        override fun channelIdle(ctx: ChannelHandlerContext, evt: IdleStateEvent) { 

            logInfo(logger) {            ctx.channel().close()            "$HERT_BEAT_TIME 秒内没有收到心跳,则断开衔接" 

            }    }    companion object { 

            private const val HERT_BEAT_TIME = 300 

        }} 

    MagicNumValidator:用于 TCP 报文的魔数校验。

    class MagicNumValidator : LengthFieldBasedFrameDecoder(Int.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH) { 

        private val logger: Logger = LoggerFactory.getLogger(this.javaClass) 

        @Throws(Exception::class) 

        override fun decode(ctx: ChannelHandlerContext, `in`: ByteBuf): Any? { 

            if (`in`.getInt(`in`.readerIndex()) !== MAGIC_NUMBER) { // 魔数校验不经过,则封锁衔接 

                logInfo(logger,"魔数校验失败"

                ctx.channel().close() 

                return null 

            } 

            return super.decode(ctx, `in`) 

        } 

        companion object { 

            private const val LENGTH_FIELD_OFFSET = 7 

            private const val LENGTH_FIELD_LENGTH = 4 

        } 

    PacketCodecHandler: 解析报文的 Handler。

    PacketCodecHandler 承袭自 ByteToMessageCodec ,它是用来处置 byte-to-message 和message-to-byte,便于解码字节音讯成 POJO 或编码 POJO 音讯成字节。

    @ChannelHandler.Sharable 

    (责任编辑:admin)