Launcher/LaunchServer/src/main/java/ru/gravit/launchserver/websocket/WebSocketFrameHandler.java

65 lines
2.4 KiB
Java
Raw Normal View History

package ru.gravit.launchserver.websocket;
2018-10-01 09:45:36 +03:00
import com.google.gson.GsonBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.concurrent.GlobalEventExecutor;
2018-10-01 10:48:24 +03:00
import ru.gravit.launchserver.LaunchServer;
import ru.gravit.launchserver.socket.Client;
import ru.gravit.utils.helper.IOHelper;
import ru.gravit.utils.helper.LogHelper;
2018-11-08 15:30:16 +03:00
import java.util.concurrent.TimeUnit;
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
2018-10-01 10:48:24 +03:00
public static LaunchServer server;
public static GsonBuilder builder = new GsonBuilder();
2018-11-08 15:30:16 +03:00
public static WebSocketService service = new WebSocketService(new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), LaunchServer.server, builder);
2019-05-09 16:00:10 +03:00
public NettyConnectContext context;
public WebSocketFrameHandler(NettyConnectContext context) {
this.context = context;
}
private Client client;
2018-11-08 15:30:16 +03:00
2018-10-01 09:45:36 +03:00
static {
service.registerResponses();
2018-10-01 09:45:36 +03:00
}
2019-05-15 14:11:22 +03:00
public void setClient(Client client) {
this.client = client;
}
2018-11-08 15:30:16 +03:00
@Override
public void channelActive(ChannelHandlerContext ctx) {
LogHelper.dev("New client %s", IOHelper.getIP(ctx.channel().remoteAddress()));
client = new Client(0);
2018-10-01 13:01:10 +03:00
service.registerClient(ctx.channel());
ctx.executor().schedule(() -> {
ctx.channel().writeAndFlush(new PingWebSocketFrame());
}, 30L, TimeUnit.SECONDS);
}
2018-09-22 17:33:00 +03:00
@Override
2019-01-15 06:32:46 +03:00
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
// ping and pong frames already handled
if (frame instanceof TextWebSocketFrame) {
2019-05-09 16:05:53 +03:00
service.process(ctx, (TextWebSocketFrame) frame, client, context.ip);
} else if ((frame instanceof PingWebSocketFrame)) {
frame.content().retain();
ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content()));
//return;
2019-05-15 14:11:22 +03:00
} else if ((frame instanceof PongWebSocketFrame)) {
LogHelper.dev("WebSocket Client received pong");
2019-05-15 14:11:22 +03:00
} else if ((frame instanceof CloseWebSocketFrame)) {
ctx.channel().close();
} else {
String message = "unsupported frame type: " + frame.getClass().getName();
throw new UnsupportedOperationException(message);
}
}
}