Netty is just a simple understanding. Please correct any mistakes.
- Why do you have a heartbeat
If a connection is not used for a long time, it will be closed to reduce the connection pressure of the server. Because the server needs to keep the connection information of the client, the client is likely to have various conditions, such as forced shutdown, disconnection, etc., which leads to the failure of connection. In this case, waste of resources on the server
- netty provides the heartbeat detection class IdleStateHandler
new IdleStateHandler(10,0, 0, TimeUnit.SECONDS) The first parameter is read timeout The second parameter is write timeout The third parameter is read-write timeout Time 0 means no monitoring
- When the heartbeat detection starts, the following methods will be triggered
The timeout detection here only detects the current class for the current class channelRead0 Method //Only read timeout is detected here. The connection will be closed after 5 times of timeout public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; System.out.println(ctx.channel().remoteAddress()+"Timeout times:"+count); String type = ""; if (event.state() == IdleState.READER_IDLE) { type = "read idle"; count++; if(count>5) { System.out.println("Timeout reached maximum, disconnect"); 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()+"Timeout type:" + type); } super.userEventTriggered(ctx, evt); }
- Here is the data received by the front desk
Heartbeat is the heartbeat data pushed by the server
If the front desk receives the data and returns a piece of data, it will be OK. Otherwise, if it is more than 5, it will be disconnected
ws.send("Heartbeat");
If the foreground wants to realize disconnection and reconnection, it should be handled in the following methods
ws.onclose = function(evt){ console.log("WebSocketClosed!"); }; ws.onerror = function(evt){ console.log("WebSocketError!"); };