From 467138ec2c82c795acf8e9bdb33d088818793b92 Mon Sep 17 00:00:00 2001 From: Gravit Date: Sat, 6 Apr 2019 14:02:06 +0700 Subject: [PATCH] =?UTF-8?q?[FIX]=20=D0=9F=D0=BE=D0=B4=D0=B4=D0=B5=D1=80?= =?UTF-8?q?=D0=B6=D0=BA=D0=B0=20Ping/pong=20WebSockets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../websocket/WebSocketFrameHandler.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/LaunchServer/src/main/java/ru/gravit/launchserver/websocket/WebSocketFrameHandler.java b/LaunchServer/src/main/java/ru/gravit/launchserver/websocket/WebSocketFrameHandler.java index d08a7c41..f01b80b8 100644 --- a/LaunchServer/src/main/java/ru/gravit/launchserver/websocket/WebSocketFrameHandler.java +++ b/LaunchServer/src/main/java/ru/gravit/launchserver/websocket/WebSocketFrameHandler.java @@ -4,14 +4,15 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.group.DefaultChannelGroup; -import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; -import io.netty.handler.codec.http.websocketx.WebSocketFrame; +import io.netty.handler.codec.http.websocketx.*; import io.netty.util.concurrent.GlobalEventExecutor; import ru.gravit.launchserver.LaunchServer; import ru.gravit.launchserver.socket.Client; import ru.gravit.utils.helper.IOHelper; import ru.gravit.utils.helper.LogHelper; +import java.util.concurrent.TimeUnit; + public class WebSocketFrameHandler extends SimpleChannelInboundHandler { public static LaunchServer server; public static GsonBuilder builder = new GsonBuilder(); @@ -31,6 +32,9 @@ public void channelActive(ChannelHandlerContext ctx) { LogHelper.debug("New client %s", IOHelper.getIP(ctx.channel().remoteAddress())); client = new Client(0); service.registerClient(ctx.channel()); + ctx.executor().schedule(() -> { + ctx.channel().writeAndFlush(new PingWebSocketFrame()); + }, 30L, TimeUnit.SECONDS); } @Override @@ -39,6 +43,16 @@ protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof TextWebSocketFrame) { service.process(ctx, (TextWebSocketFrame) frame, client); + } else if ((frame instanceof PingWebSocketFrame)) { + frame.content().retain(); + ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content())); + //return; + } + else if ((frame instanceof PongWebSocketFrame)) { + LogHelper.dev("WebSocket Client received pong"); + } + else if ((frame instanceof CloseWebSocketFrame)) { + ctx.channel().close(); } else { String message = "unsupported frame type: " + frame.getClass().getName(); throw new UnsupportedOperationException(message);