riku
2019-09-19 58a16c3340f92a1ec0362565020f31de56faaf3e
src/main/kotlin/com/flightfeather/obd/socket/ServerHandler.kt
@@ -3,6 +3,10 @@
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() {
@@ -10,6 +14,7 @@
    override fun channelRegistered(ctx: ChannelHandlerContext?) {
        super.channelRegistered(ctx)
//        ctx?.fireChannelActive()
    }
    override fun channelActive(ctx: ChannelHandlerContext?) {
@@ -18,11 +23,33 @@
    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
        super.channelRead(ctx, msg)
        val attribute = ctx?.channel()?.attr(attributeKey)?.apply {
            if (get() == null) {
//                set()
        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?) {
@@ -34,6 +61,7 @@
    }
    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        super.exceptionCaught(ctx, cause)
        cause?.printStackTrace()
        ctx?.close()
    }
}