package com.anyun.exam.lib.net
|
|
import android.util.Log
|
import io.netty.channel.ChannelHandler
|
import io.netty.channel.ChannelHandlerContext
|
import io.netty.channel.ChannelInboundHandlerAdapter
|
import io.netty.util.AttributeKey
|
|
|
|
@ChannelHandler.Sharable
|
class ConnectionWatchdog : ChannelInboundHandlerAdapter() {
|
internal var KEY = AttributeKey.valueOf<NettyTcpClient>("TcpClient")
|
/**
|
* channel链路每次active的时候,将其连接的次数重新置0
|
*/
|
override fun channelActive(ctx: ChannelHandlerContext) {
|
val tcpClient = ctx.channel().attr(KEY).get()
|
Log.i(Constant.LOGTAG, "TCP已经连接至[${tcpClient.host}:${tcpClient.port}]")
|
tcpClient.autoConnect = true
|
tcpClient.isConnected = true
|
tcpClient.isAuthentication = false
|
tcpClient.dataStatus = NettyTcpClient.WAIT_AUTH
|
ctx.fireChannelActive()
|
}
|
|
override fun channelInactive(ctx: ChannelHandlerContext) {
|
val tcpClient = ctx.channel().attr(KEY).get()
|
tcpClient.isConnected = false
|
ctx.fireChannelInactive()
|
if(tcpClient.autoConnect) {
|
Log.i(Constant.LOGTAG, "TCP链接已断开[${tcpClient.host}:${tcpClient.port}] 2秒后重新连接")
|
Thread.sleep(2000)
|
tcpClient.connect(tcpClient.context)
|
}
|
else
|
{
|
Log.i(Constant.LOGTAG, "TCP链接已断开[${tcpClient.host}:${tcpClient.port}] 需要手动重新连接")
|
}
|
}
|
}
|