11, Netty realizes the long connection between server and client through WebSocket programming

1, What is Websocket?

1. Application scenario of websocket Technology

Use java technology to quickly learn a simple online chat room system. The system has strong scalability. It can make online customer service system, web version of wechat, QQ instant messaging system, etc. according to business needs, use more popular technology and adopt building block programming ideas.

The real-time push technology in the web field is also called Realtime technology. The purpose of this technology is to bypass the user and obtain real-time updates without refreshing the browser. It has a wide range of application prospects, such as online chat room, online customer service system, comment system, WebIM, etc.

2. Overview of websocket protocol

webSocket protocol is a new protocol of HTML5. He realized full duplex communication between browser and server. The initial handshake needs to be completed with the help of HTTP request.

websocket is an Internet technology that realizes the full duplex communication from server to client.

It is a protocol for full duplex communication on a single TCP connection. webSocket communication protocol was defined as standard RFC 6455 by IETF in 2011, and webSocket API was defined as standard by W3c.

3. Difference between full duplex and simplex

Full duplex: a term for communication transmission. Communication allows data to be transmitted simultaneously in two directions. Its capability is equivalent to the combination of two simplex communication modes. Full duplex refers to the two-way transmission of signals at the same time (instantaneously) (a - > b, B-A) refers to the simultaneous transmission of a - > b, and B - > A is instantaneously synchronized.

Simplex and half duplex. The so-called half duplex means that only one action occurs in a period of time. For example, only one carriage can pass through a narrow road at the same time. When there are two carriages at present, one needs to wait for the other to pass. This example vividly illustrates the principle of half duplex. Early walkie talkies and early Phase I hubs and other equipment are based on half duplex products. With the continuous progress of technology, the half duplex union gradually withdrew from the historical stage

4. Push technology and pull technology (understand)

Push technology is a mechanism established on the client server, which is the technology that the server actively sends information to the client, just like broadcasting by a radio station.
Compared with the traditional pull Pull technology, the main difference is that the push Push technology is simultaneous interpreting information from the server to the client by the server. While pulling PULL technology is the client's active request for information. The advantage of PUSH technology lies in the initiative and timeliness of information.
In short, compared with the server, the pull technology passively provides data to the client, and the push technology actively provides data to the client

5. Internet technology

Definition of Internet technology: Internet technology refers to an information technology developed and established on the basis of computer technology; IT for short

This technology integrates the scattered resources on the Internet into an organic whole, realizes the comprehensive sharing and organic cooperation of resources, and enables people to use the overall ability of resources transparently and obtain information on demand.

6. Advantages of Wenbsocket

In the past, no matter how to use HTTP polling or TCP long connection to make online chat system, it has natural defects. With the development of Html5, there is a new protocol Websocket protocol, which can realize full duplex communication between browser and server. It can do that browser and server only need one handshake, and then a handshake is formed between browser and server A fast channel. Data can be transmitted between the two. The characteristics of this new protocol are just suitable for this kind of online instant messaging.

Implementation of traditional Http protocol:

The http protocol can request multiple times, because the connection will be closed after each request. The next time you re request data, you need to open the connection again

Traditional Socket technology:

Long connection

Client - connect first - server

Benefits: it can realize two-way communication between client and server

Disadvantages: if everyone does not speak, it will cause a waste of resources

Other features include:

(1) Based on TCP protocol, the server-side implementation is relatively easy.

(2) It has good compatibility with HTTP protocol. The default ports are 80 and 443, and the HTTP protocol is used in the handshake stage. Therefore, it is not easy to shield the handshake and can pass through various HTTP proxy servers.

(3) The data format is light, the performance overhead is small, and the communication is efficient.

(4) You can send text or binary data.

(5) There is no homology restriction, and the client can communicate with any server.

(6) The protocol identifier is ws (wss if encrypted) and the server URL is the URL.


2, Example requirements and Implementation:

  1. Http protocol is stateless. The request between browser and server responds once, and the connection will be re created next time
  2. Requirements: realize full duplex interaction of long connection based on webSocket
  3. Change the constraint of multiple requests of Http protocol to realize a long connection, and the server can send messages to the browser
  4. The client browser and the server will perceive each other. For example, when the server is closed, the browser will perceive. Similarly, when the browser is closed, the server will perceive
  5. Operation interface

2.1 MyServer code

package com.netty.webSocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.nio.channels.ServerSocketChannel;

public class MyServer {
    public static void main(String[] args) throws Exception {

        //Create two thread pool groups
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //Create netty startup class
        ServerBootstrap serverBootstrap=new ServerBootstrap();
        try {
            serverBootstrap.group(bossGroup, workGroup)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //Because it is based on http, http codec and decoder are used
                            pipeline.addLast(new HttpServerCodec());
                            //It is written in block mode, and a chunkedWrite processor is added
                            pipeline.addLast(new ChunkedWriteHandler());
                            * explain:
                            *    1,Because http data is segmented during transmission, the httpObjectAggregator can aggregate multiple segments
                            *    2,This is why when a browser sends a large amount of data, it makes multiple http requests
                            * */
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            * explain:
                            *    1,Corresponding to webSocket, its data is transmitted in the form of frame
                            *    2,You can see that there are six subclasses under websocketFrame
                            *    3,When the browser requests, ws://localhost:7000/hello indicates the url of the request
                            *    4,WebSocketServerProtocolHandler The core function is to upgrade an http protocol to ws protocol, that is, websocket protocol, to maintain a long connection
                            * */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            //Custom handler to handle business logic
                            pipeline.addLast(new MyTestWebSocketFrameHandler());
            //Start the server
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
        }finally {

2.2 code

package com.netty.webSocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

//Here, the TextWebSocketFrame type represents a text frame
public class MyTestWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("Message received by server:" + msg.text());
        //Reply message
        ctx.channel().writeAndFlush(new TextWebSocketFrame("Server time"+ LocalDateTime.now()+msg.text()));

    //When the web client connects, the
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //id represents a unique value, LongText is unique, and ShortTest is not unique
        System.out.println("handlerAdded Called" + ctx.channel().id().asLongText());
        System.out.println("handlerAdded Called" + ctx.channel().id().asShortText());
        ctx.channel().writeAndFlush(new TextWebSocketFrame("Connection succeeded..."));

    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved Called" + ctx.channel().id().asLongText());
        ctx.channel().writeAndFlush("Connection closed.....");

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("Abnormal occurrence" + cause.getMessage());
        ctx.close();//Close connection

2.3 hello.tml code

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    var socket;
    //Judge whether the current browser supports websocket
        //GO ON
        socket = new WebSocket("ws://localhost:7000/hello");
        //Equivalent to channelread0. EV receives the message returned by the server
        //Triggered when there is a message
        socket.onmessage=function (ev){
            var rt=document.getElementById("responseText");
            //Triggered when the connection is open
        //Triggered when the connection is closed
        socket.onclose=function (ev){
            var rt=document.getElementById("responseText");
            rt.value=rt.value+"\n"+"The connection is closed...";
        socket.onopen=function (ev){
            var rt=document.getElementById("responseText");
            rt.value="The connection is open....";
    }else {
        alert("The current browser does not support Websocket");

    //Send message to server
    function  send(message){
       if(!window.socket){//First judge whether the socket is created
           return ;
           //Send message through socket
           alert("The current browser does not support websocket!");
<form onsubmit="return false">
    <textarea name="message" style="height: 300px;width: 300px"></textarea>
    <input type="button" value="send message" onclick="send(this.form.message.value)"/>
    <textarea id="responseText" style="height:300px;width:300px"></textarea>
    <input type="button" value="Empty content" onclick="document.getElementById(responseText)">

2.4 results

💥 Recommended reading 💥

Part 1: 10. Netty heartbeat mechanism of netty core technology

Next: 10. Asynchronous model analysis of Netty core technology

Tags: Netty network websocket

Posted on Tue, 09 Nov 2021 06:24:56 -0500 by alconebay