yy1717
2024-02-28 27fc91fbe8f88b6885356e68828cfe1ce1db7601
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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}] 需要手动重新连接")
        }
    }
}