riku
2021-06-30 5353617c7b2135ab00f98d8e05b2f8dfb2e096ed
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.flightfeather.uav.socket
 
import com.flightfeather.uav.socket.processor.BaseProcessor
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.util.AttributeKey
import java.lang.StringBuilder
import java.text.SimpleDateFormat
import java.util.*
 
 
class ServerHandler(private val processor: BaseProcessor) : ChannelInboundHandlerAdapter() {
 
    val attributeKey = AttributeKey.valueOf<String>("deviceCode")
 
    override fun channelRegistered(ctx: ChannelHandlerContext?) {
        super.channelRegistered(ctx)
        println("------【${processor.tag}】IP连接:[ip:${ctx?.channel()?.remoteAddress()}] ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}")
//        ctx?.fireChannelActive()
    }
 
    override fun channelActive(ctx: ChannelHandlerContext?) {
        println("------【${processor.tag}】IP激活:[ip:${ctx?.channel()?.remoteAddress()}] ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}")
        super.channelActive(ctx)
    }
 
    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
        super.channelRead(ctx, msg)
        println("------【${processor.tag}】收到的原始数据:[ip:${ctx?.channel()?.remoteAddress()}] ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}")
 
        var str = ""
 
        when (msg) {
            is ByteArray -> {
                val sb = StringBuilder()
 
                msg.forEach {
                    var a = 0
                    a = if (it < 0) {
                        it + 256
                    } else {
                        it.toInt()
                    }
                    val s = if (a < 16) {
                        "0${a.toString(16)}"
                    } else {
                        a.toString(16)
                    }
                    sb.append(s).append(" ")
                }
                sb.deleteCharAt(sb.length - 1)
 
                str = sb.toString()
            }
            is String -> str = msg
        }
 
        println(str)
 
        if (str.isNotEmpty()) {
            processor.dealStringMsg(str, ctx)
        }
    }
 
    override fun channelReadComplete(ctx: ChannelHandlerContext?) {
        super.channelReadComplete(ctx)
    }
 
    override fun channelInactive(ctx: ChannelHandlerContext?) {
        println("------【${processor.tag}】端口有IP不活动:[ip:${ctx?.channel()?.remoteAddress()}] ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}")
        super.channelInactive(ctx)
    }
 
    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        cause?.printStackTrace()
        ctx?.close()
    }
}