Skip to content

Instantly share code, notes, and snippets.

@Mr00Anderson
Created October 23, 2020 12:40
Show Gist options
  • Save Mr00Anderson/4c10ec4cb7e8b446f1e3951748e1c98e to your computer and use it in GitHub Desktop.
Save Mr00Anderson/4c10ec4cb7e8b446f1e3951748e1c98e to your computer and use it in GitHub Desktop.
nettyio websockets nettyiowebsockets
package com.virtual_hex.network;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class HTTPInitializer extends ChannelInitializer<SocketChannel> {
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("httpServerCodec", new HttpServerCodec());
pipeline.addLast("httpHandler", new HttpServerHandler());
}
}
package com.virtual_hex.network;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
public class HttpServerHandler extends ChannelInboundHandlerAdapter {
WebSocketServerHandshaker handshaker;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) msg;
System.out.println("Http Request Received");
HttpHeaders headers = httpRequest.headers();
System.out.println("Connection : " +headers.get("Connection"));
System.out.println("Upgrade : " + headers.get("Upgrade"));
if ("Upgrade".equalsIgnoreCase(headers.get(HttpHeaderNames.CONNECTION)) &&
"WebSocket".equalsIgnoreCase(headers.get(HttpHeaderNames.UPGRADE))) {
//Adding new handler to the existing pipeline to handle WebSocket Messages
ctx.pipeline().replace(this, "websocketHandler", new WebSocketHandler());
System.out.println("WebSocketHandler added to the pipeline");
System.out.println("Opened Channel : " + ctx.channel());
System.out.println("Handshaking....");
//Do the Handshake to upgrade connection from HTTP to WebSocket protocol
handleHandshake(ctx, httpRequest);
System.out.println("Handshake is done");
}
} else {
System.out.println("Incoming request is unknown");
}
}
/* Do the handshaking for WebSocket request */
protected void handleHandshake(ChannelHandlerContext ctx, HttpRequest req) {
WebSocketServerHandshakerFactory wsFactory =
new WebSocketServerHandshakerFactory(getWebSocketURL(req), null, true);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
}
protected String getWebSocketURL(HttpRequest req) {
System.out.println("Req URI : " + req.getUri());
String url = "ws://" + req.headers().get("Host") + req.getUri() ;
System.out.println("Constructed URL : " + url);
return url;
}
}
package com.virtual_hex.network;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.*;
public class WebSocketHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof WebSocketFrame) {
System.out.println("This is a WebSocket frame");
System.out.println("Client Channel : " + ctx.channel());
if (msg instanceof BinaryWebSocketFrame) {
System.out.println("BinaryWebSocketFrame Received : ");
System.out.println(((BinaryWebSocketFrame) msg).content());
} else if (msg instanceof TextWebSocketFrame) {
System.out.println("TextWebSocketFrame Received : ");
ctx.channel().writeAndFlush(
new TextWebSocketFrame("Message recieved : " + ((TextWebSocketFrame) msg).text()));
System.out.println(((TextWebSocketFrame) msg).text());
} else if (msg instanceof PingWebSocketFrame) {
System.out.println("PingWebSocketFrame Received : ");
System.out.println(((PingWebSocketFrame) msg).content());
} else if (msg instanceof PongWebSocketFrame) {
System.out.println("PongWebSocketFrame Received : ");
System.out.println(((PongWebSocketFrame) msg).content());
} else if (msg instanceof CloseWebSocketFrame) {
System.out.println("CloseWebSocketFrame Received : ");
System.out.println("ReasonText :" + ((CloseWebSocketFrame) msg).reasonText());
System.out.println("StatusCode : " + ((CloseWebSocketFrame) msg).statusCode());
} else {
System.out.println("Unsupported WebSocketFrame");
}
}
}
}
package com.virtual_hex.network;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class WebSocketServerProto {
private static final int PORT = 9000;
public static void main(String[] args) {
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 1024);
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new HTTPInitializer());
Channel ch = b.bind(PORT).sync().channel();
ch.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment