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)