1、开启服务器noi 服务监听
final ServerHandler serverHandler = new ServerHandler();
// 主线程组,用于接受客户端的连接,但是不做任何处理,跟老板一样
EventLoopGroup bossGroup = new NioEventLoopGroup();
// 从线程组,主线程组会把任务丢给它,让从线程组去做相应的处理
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(PORT)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(serverHandler);
}
});
ChannelFuture channelFuture = serverBootstrap.bind().sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
2、channel 缓存和用户进行绑定
客户端上线后,立即发送后台用户tocken消息给后台,后台获取到用户id和channel 1对1关系。
3、ping pong 心跳判断用户是否掉线
服务器每60秒定时发送ping 命令给所有客户端
如果用户在线返回pong指令 更新返回给服务端 lastHeartBeatTime
/**
* 刷新心跳时间
* @param channel
*/
public static void refreshLastHeartBeatTime(Channel channel) {
Long now = System.currentTimeMillis();
channel.attr(ATTR_KEY_LAST_HEARTBEAT_TIME).set(now.toString());
}
如果channel lastHeartBeatTime超过90秒判断channel 离线 用户掉线。