All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.neko233.virtualRouter.server.handler.JsonObjDispatcherHandler.kt Maven / Gradle / Ivy

package com.neko233.virtualRouter.server.handler

import com.neko233.virtualRouter.core.RouteMessage
import com.neko233.virtualRouter.core.RouterSessionManager
import com.neko233.virtualRouter.core.businessHandler.HandleRouteStrategy
import com.neko233.virtualRouter.core.utils.JsonUtils
import com.neko233.virtualRouter.core.utils.NettyUtils
import com.neko233.virtualRouter.server.constant.NettyAttrConstant
import com.neko233.virtualRouter.server.strategy.RouteServerStrategyFactory
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import java.net.SocketException

class JsonObjDispatcherHandler : ChannelInboundHandlerAdapter() {

    companion object {
        val LOGGER = LoggerFactory.getLogger(this::class.java)!!
    }

    override fun channelRead(
        ctx: ChannelHandlerContext,
        jsonMsg: Any?,
    ) {

        val channel = ctx.channel()
        if (jsonMsg !is String) {
            LOGGER.error("msg 不是 String 类型. msg = {}", jsonMsg)
            return
        }

        val routeMessage: RouteMessage = RouteMessage.decode(jsonMsg)

        // 发送给
        val msgType = routeMessage.messageType
        if (msgType == null) {
            LOGGER.error(
                "msgType=null 没有传入. remote host={}, msg={}",
                NettyUtils.getRemoteHostStr(channel),
                JsonUtils.serialize(routeMessage)
            )
            return
        }
        val fromRouteId = routeMessage.fromRouteId
        val toRouteId = routeMessage.toRouteId


        val strategy: HandleRouteStrategy? = RouteServerStrategyFactory.instance.get(msgType)
        if (strategy == null) {
            LOGGER.error("没找到 fromRouteId={}, toRouteId = {}, strategyName={} ", fromRouteId, toRouteId, msgType)
            return
        }

        strategy.handleReq(routeMessage, channel)
    }


    @Deprecated("Deprecated in Java")
    override fun exceptionCaught(
        ctx: ChannelHandlerContext?,
        cause: Throwable?,
    ) {
        ctx ?: return

        if (cause is SocketException) {
            val info = NettyUtils.getNettyRemoteInfo(ctx)
            LOGGER.error("socket 连接突然中断! remote ip = {}, port = {}", info.host, info.port)

            val attr = ctx.channel().attr(NettyAttrConstant.NETTY_ATTR_ROUTE_ID)
            val routeId = attr.get()

            if (StringUtils.isBlank(routeId)) {
                return
            }

            RouterSessionManager.Instance.removeSession(routeId)
            return
        }

        LOGGER.error("未捕获的异常. ", cause)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy