In order to realize the push technology, a certain system of the company used Ajax polling. In this way, the browser needs to continuously send requests to the server, which obviously wastes a lot of bandwidth and other resources. Therefore, I studied WebSocket, which will be introduced in detail in this paper.

What is WebSocket?

WebSocket is a full-duplex communication protocol on a single TCP connection provided by HTML5, which can save server resources and bandwidth better and communicate in a more real-time manner.

WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and the server only need to complete a handshake, they can directly create a persistent connection, and two-way data transmission.

SpringBoot integrates WebSocket

Create a new Spring Boot project spring-boot-websocket and follow these steps.

  1. Pom.xml introduces jar packages
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>Copy the code
  1. Create a new WebSocket configuration class

This configuration class detects beans annotated @ServerEndpoint and registers them. The configuration class code looks like this:

@configuration Public class WebSocketConfig {/** * Inject this ServerEndpointExporter object into the Spring container * equivalent to XML:  * <beans> * <bean id="serverEndpointExporter" class="org.springframework.web.socket.server.standard.ServerEndpointExporter"/> * </beans> * <p> * Detect all beans annotated with @Serverendpoint and register them. * * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        System.out.println("I was injected.");
        returnnew ServerEndpointExporter(); }}Copy the code
  1. Create a new WebSocket handler class

This class needs to use @Serverendpoint. This class listens for connections to be established and closed, messages to be received, etc. The code is as follows:

@ServerEndpoint(value = "/ws/asset")
@Component
public class WebSocketServer {

    @PostConstruct
    public void init() {
        System.out.println("The websocket loading");
    }
    private static Logger log= LoggerFactory.getLogger(WebSocketServer.class); private static final AtomicInteger OnlineCount = new AtomicInteger(0); // A thread-safe Set for a concurrent package, used to hold Session objects corresponding to each client. private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>(); / / @onopen public void OnOpen (Session Session) {sessiononset. Add (Session); int cnt = OnlineCount.incrementAndGet(); // Add 1 log.info("Connection added, current connection count: {}", cnt);
        SendMessage(session, "Connection successful"); } @onclose public void OnClose (Session Session) {sessiononset. int cnt = OnlineCount.decrementAndGet(); log.info("Connection closed, current connection count: {}", cnt); } /** * @param message */ @onMessage public void OnMessage (String message, Session session) { log.info("Message from client: {}",message);
        SendMessage(session, "Received message, message content:"+message); } @param session @param error @onError public void OnError (session session, Throwable error) { log.error(Error: {}, Session ID: {},error.getMessage(),session.getId()); error.printStackTrace(); } /** * sends messages. Practice shows that session changes every time the browser refreshes. * @param session * @param message */ public static void SendMessage(Session session, String message) { try { // session.getBasicRemote().sendText(String.format("%s (From Server, Session ID=%s)",message,session.getId()));
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("Error sending message: {}", e.getMessage()); e.printStackTrace(); }} /** * Group message @param message @throws IOException */ public static void BroadCastInfo(String message) throws IOException {for (Session session : SessionSet) {
            if(session.isOpen()){ SendMessage(session, message); }} /** * Specifies the Session to send messages * @param sessionId * @param message * @throws IOException */ public static void SendMessage(String message,String sessionId) throws IOException { Session session = null;for (Session s : SessionSet) {
            if(s.getId().equals(sessionId)){
                session = s;
                break; }}if(session! =null){ SendMessage(session, message); }else{
            log.warn("The session with your specified ID was not found: {}",sessionId); }}}Copy the code
  1. Create a new HTML

At present, most browsers support WebSocket, such as Chrome, Mozilla,Opera and Safari. WebSocket connection is established in HTML pages and message receiving is monitored. The page code is as follows:

<html>
<head>
    <meta charset="UTF-8"> <title>websocket test </title> <script SRC ="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <style type="text/css"> h3,h4{ text-align:center; } </style> </head> <body> <h3>WebSocket test, client received the following message: </h3> <textarea id ="messageId" readonly="readonly" cols="150" rows="30" >

</textarea>


<script type="text/javascript">
    var socket;
    if (typeof (WebSocket) == "undefined") {
        console.log("Regret: Your browser does not support WebSocket");
    } else {
        console.log("Congratulations: Your browser supports WebSocket"); // Set up a connection with the port. // Note that WS and WSS use different ports. WSS can not be used, the browser opened WebSocket error //ws corresponds to HTTP, WSS corresponds to HTTPS. socket = new WebSocket("ws://localhost:8080/ws/asset"); // connect to open event socket.onopen =function() {
            console.log("Socket open");
            socket.send("Message sending Test (From Client)"); }; // Received message event socket. onMessage =function(msg) {
            $("#messageId").append(msg.data+ "\n"); console.log(msg.data ); }; // Connection closing event socket.onclose =function() {
            console.log("Socket closed"); }; // An error event socket.onerror = occurredfunction() {
            alert("Socket error"); } // Close connection window.unload= when window is closedfunction() {
            socket.close();
        };
    }
</script>

</body>
</html>Copy the code

Three, check the running effect

Start the SpringBoot project

  1. Open the home page

When the home page of the local browser is http://localhost:8080/, the WebSocket test page is displayed, and connection logs are displayed in the background.

The number of connections is 1 and the sessionId is 0. ProcedureCopy the code
  1. Sends messages to clients

From the above log, you can see the client connection sessionId. When I test the sessionId is 0, then the browser can access the following interface to send messages to the client.

/ / parameters description: id: sessionID / / parameter description: message: the message content at http://localhost:8080/api/ws/sendOne? Id =0&message= Hello Java chatterCopy the code

Send message gifs

By this time SpringBoot integration WebSocket function has been fully realized.

Complete source address: https://github.com/suisui2019/springboot-study