com.neko233.virtualRouter.core.RouterSession.kt Maven / Gradle / Ivy
package com.neko233.virtualRouter.core
import com.alibaba.fastjson2.JSON
import com.neko233.virtualRouter.core.constant.RouteMessageTypeEnum
import com.neko233.virtualRouter.core.utils.JsonUtils
import com.neko233.virtualRouter.core.utils.NettyUtils
import io.netty.buffer.ByteBuf
import io.netty.channel.Channel
class RouterSession(
val routerId: String, // 路由id
val socketChannel: Channel, // 网络通道
val rpcServerInfo: RpcServerInfo, // rpc 服务器信息
) {
// 最后心跳的时间
var lastHeartBeatTimeMs: Long = System.currentTimeMillis()
private set(value) {
field = value
}
fun refreshHeartBeat() {
this.lastHeartBeatTimeMs = System.currentTimeMillis()
}
fun writeAndFlush(routeMessage: RouteMessage) {
val encode = routeMessage.encode()
socketChannel.writeAndFlush(encode)
}
fun writeAndFlush(data: ByteBuf) {
// 增加引用计数
data.refCnt().inc()
socketChannel.writeAndFlush(data)
}
fun getHost(): String {
return NettyUtils.getRemoteIp(socketChannel) ?: ""
}
fun getPort(): Int {
return NettyUtils.getRemotePort(socketChannel)
}
fun getRpcHost(): String {
return rpcServerInfo.host
}
fun getRpcPort(): Int {
return rpcServerInfo.port
}
/**
* 发送哪些 RouteClient 已经失联了
*/
fun sendWhichRouteClientOffline(toRemoteRouteIdList: List) {
val remoteRouteIdJson = JsonUtils.serialize(toRemoteRouteIdList)
val routeMessage =
RouteMessage(
fromRouteId = this.routerId,
toRouteId = this.routerId,
messageType = RouteMessageTypeEnum.RemoveRouteNode,
data = remoteRouteIdJson
)
writeAndFlush(routeMessage)
}
fun getRemoteHostStr(): String {
val ip = NettyUtils.getRemoteIp(socketChannel)
val port = NettyUtils.getRemotePort(socketChannel)
return "${ip}:${port}"
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy