riku
2020-06-02 9a5f9bfc4f4b153dd0175c63f563d8047e1e2515
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
package com.flightfeather.uav.socket
 
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 : ChannelInboundHandlerAdapter() {
 
    val attributeKey = AttributeKey.valueOf<String>("deviceCode")
 
    override fun channelRegistered(ctx: ChannelHandlerContext?) {
        super.channelRegistered(ctx)
        println("------端口有IP连接:[ip:${ctx?.channel()?.remoteAddress()}] ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}")
//        ctx?.fireChannelActive()
    }
 
    override fun channelActive(ctx: ChannelHandlerContext?) {
        println("------端口有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)
 
        val sb = StringBuilder()
 
        if (msg is ByteArray) {
            println("------收到的原始数据:[ip:${ctx?.channel()?.remoteAddress()}] ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}")
            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)
                }
                print("$s ")
                sb.append(s).append(" ")
            }
            sb.deleteCharAt(sb.length - 1)
        }
        val str = sb.toString()
        if (str.isNotEmpty()) {
            MessageManager().dealStringMsg(str, ctx)
        }
 
    }
 
    override fun channelReadComplete(ctx: ChannelHandlerContext?) {
        super.channelReadComplete(ctx)
    }
 
    override fun channelInactive(ctx: ChannelHandlerContext?) {
        println("------端口有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()
    }
}