对Netty只是简单的了解,有过错的地方请望指正。
- 为什么要有心跳
发现长期不用的连接,就关闭掉,减轻服务器的连接压力。
因为服务器要保留客户端的连接信息,客户端很可能出现各种状况,例如强制关掉,断网等导致连接不上,这时候浪费就浪费掉服务端的资源
- netty提供了心跳检测类IdleStateHandler
new IdleStateHandler(10,0, 0, TimeUnit.SECONDS)
第一个参数是读超时
第二个参数是写超时
第三个参数是读写超时
时间为0表示不监控
- 当心跳检测出发的时候会触发下面的方法
这里的超时检测只对当前类有检测当前类的channelRead0方法
这里只检测读超时,超时时间过5次后会关闭这个连接
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
System.out.println(ctx.channel().remoteAddress()+"超时次数:"+count);
String type = "";
if (event.state() == IdleState.READER_IDLE) {
type = "read idle";
count++;
if(count>5) {
System.out.println("超时次数达到最大值了,断开连接");
ChannelManager.removeChannelByChannel(ctx.channel());
ctx.channel().close();
}
} else if (event.state() == IdleState.WRITER_IDLE) {
type = "write idle";
count=0;
} else if (event.state() == IdleState.ALL_IDLE) {
type = "all idle";
count=0;
}
ctx.writeAndFlush(new TextWebSocketFrame("Heartbeat")).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
System.out.println( ctx.channel().remoteAddress()+"超时类型:" + type);
}
super.userEventTriggered(ctx, evt);
}
- 这里是前台收到的数据
Heartbeat是服务端推送过来的心跳数据
前台收到数据了返回一条数据回去就就可以了,不然超过5此会断开连接的
ws.send("Heartbeat");
前台如果要实现个断开重连则在以下方法进行处理
ws.onclose = function(evt){
console.log("WebSocketClosed!");
};
ws.onerror = function(evt){
console.log("WebSocketError!");
};