一、建立通道
image.png
- 客户端的请求登录
- 服务端的处理登录(和http登录接口类似)
二、关闭通道
image.png
三、事件触发器
3.1、ClientHandler
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
ProtobufData.Task pingPack = TaskPackage.heartBeatPing();
ctx.channel().writeAndFlush(pingPack);
}
}
super.userEventTriggered(ctx, evt);
}
3.2、NettyServerHandler
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
if (idleStateEvent.state() == IdleState.READER_IDLE && ctx.channel().hasAttr(ChannelSessionManager.SESSION)) {
UserInfo userInfo = ChannelSessionManager.getChannelSession(ctx.channel(), UserInfo.class);
String roomId = userInfo.getAppKey() + Constants.ROOM_SEPARATOR_WORD + userInfo.getRoomId();
String userId = userInfo.getUserId();
cleanChannel(roomId, userId, ctx.channel().id());
}
}
ctx.channel().close();
super.userEventTriggered(ctx, evt);
}
四、异常事件
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.channel().close();
}
网友评论