This is the 7th day of my participation in the August Text Challenge.More challenges in August

Before we practice Netty implementation of Http small case, today we start the implementation of Websocket, before the actual combat to understand the introduction of Websocetk!

What is Websocket?

WebSocket Changes from the standard HTTP or HTTPS protocol to WebSocket using Upgrade Handshake. Therefore, applications that use WebSocket will always start with HTTP/S and then upgrade. When this happens depends on the application; It can be at startup, or when a particular URL is requested.

In our application, we upgrade the protocol to WebSocket only when the URL request ends in “/ws”. Otherwise, the server will use basic HTTP/S. Once the connection is upgraded the WebSocket will be used to transfer all data.

How to handle Websocket?

  1. The client connects to the server
  2. HTTP request page or Websocket”Upgrade Handshake”
  3. The server handles the client that initiates the connection
  4. Handle Websocket”Upgrade Handshake “if the URL is “/ws”
  5. After the upgrade handshake is complete, a chat message is sent through the WebSocket

Practical:

Four pages:

Step 1, create the WWSServer page

/** * @version 1.0 * @date 2021/8/31 19:44 */ public class WWSServer {int port = 8081; Public void start() {// Define a pair of thread groups // main thread groups for receiving client connections, EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap Server = new ServerBootstrap(); // Bind two thread groups server.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new WSServerInitialzer()); ChannelFuture Future = server.bind(port).sync(); // Start the server and set 8088 to the port number. System.out.println(" server start up on port : " + port); Future.channel ().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } the finally {/ / graceful exit, release the thread pool resources bossGroup. ShutdownGracefully (); workerGroup.shutdownGracefully(); }}}Copy the code

Step 2: Create the WSServerInitializer page

/** * @version 1.0 * @date 2021/8/31 19:46 */ public class WSServerInitializer extends ChannelInitializer<SocketChannel>  { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // Handle HTTP message codec pipeline. AddLast ("httpServerCodec", new httpServerCodec ()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); / / add support for httpWebsocket pipeline. AddLast (new WebSocketServerProtocolHandler ("/ws ")); // Custom handler pipeline.addLast(new ChatHandler()); }}Copy the code

Step 3, create the ChatHandler page

/** * @Description: Handler * @version 1.0 * @date 2021/8/31 19:56 */ Public Class ChatHandler extends SimpleChannelInboundHandler < TextWebSocketFrame > {/ / record and manage all the client channel private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame MSG) throws Exception {// Obtain the message transmitted by the client. String Content = msg.text(); System.out.println(" receive data with id "+ ctx.channel().id() +" : "+ content); WriteAndFlush (new TextWebSocketFrame(" I am Websocket Server, I received your message as :" + content)); } // Get the client channel, @override public void handlerAdded(ChannelHandlerContext CTX) throws Exception { clients.add(ctx.channel()); } @override public void removed (ChannelHandlerContext CTX) throws Exception { System.out.println(" The client is disconnected, and the corresponding channel id is: " + ctx.channel().id().asLongText()); System.out.println(" the client is disconnected, the short ID of the channel is: "+ ctx.channel().id().asshorttext ()); }}Copy the code

The fourth step calls the start method

Testing:

Directly find an online test websocket test, and successful feedback results