Netty supports Websocket at the protocol level, and only needs to add the corresponding handler to the service.

Server code:

public class MyServer { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketChannelInitializer()); ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(8192)); pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); pipeline.addLast(new TextWebSocketFrameHandler()); } } public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected Void channelRead0(ChannelHandlerContext CTX, TextWebSocketFrame MSG) throws Exception {system.out.println (" Received message: " + msg.text()); Ctx.channel ().writeAndFlush(new TextWebSocketFrame(" server time: "+ localDatetime.now ())); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { System.out.println("handlerAdded:" + ctx.channel().id().asLongText()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { System.out.println("handlerRemoved:" + ctx.channel().id().asLongText()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }}Copy the code

The WebSocket protocol is based on HTTP, and the client uses front-end HTML code directly:

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta Charset ="UTF-8"> <title>WebSocket client </title> </head> <body> <script type="text/javascript"> var socket; if (window.WebSocket) { socket = new WebSocket("ws://localhost:8899/ws"); socket.onmessage = function (event) { var ta = document.getElementById("responseText"); ta.value = ta.value + "\n" + event.data; } socket.onopen = function (event) { var ta = document.getElementById("responseText"); Ta. Value = ta. Value + "\n" + "Connection open "; } socket.onclose = function (event) { var ta = document.getElementById("responseText"); Ta. Value = ta. Value + "\n" + "Connection closed "; } function send(message) { if(! WebSocket) { return; } if (socket.readyState == WebSocket.OPEN) { socket.send(message); } else {alert(" connection not yet open "); }}} else {alert(' browser does not support WebSocket'); } </script> <form onsubmit="return false;" > <textarea name="message" style="width: 400px; height: < span style =" box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; white-space: normal;" </h3> <textarea id="responseText" style="width: 400px; height: 200px"></textarea> <input type="button" onclick="javascript: Document.getelementbyid ('responseText').value= "" value=" "</form> </body> </ HTML >Copy the code

Final result:

Websocket is a full-duplex protocol where the server can proactively push messages to the client: