WebSocket is introduced

What is the WebSocket

WebSocket is a protocol that belongs to IETF.

1.HTTP is an application protocol that runs on the TCP transport layer, while WebSocket is an application protocol that negotiates connections through HTTP and runs independently on the TCP transport layer.

2.Websocket is a persistent protocol, as opposed to HTTP, which is not persistent.

3.Websocket defines a communication standard. Through a handshake mechanism, a TCP connection can be established between the client and the server to facilitate their communication

Why WebSocket

The WebSocket feature was added for better, more flexible, lightweight communication with the server. Because WebSocket provides a simple message specification that can be adapted to long connections more quickly, the HTTP protocol itself can now do this, but it is not very portable.

The biggest feature of WebSocket is to achieve full-duplex communication: the client can push messages to the server in real time, and the server can also push messages to the client in real time.

WebSocket can do chat room, stock real-time price display and other applications

Correct WebSocket misconceptions

WebSocket is an application protocol, and we often see HTML5 WebSocket as an API, so don’t confuse it.

HTML5 in the broad sense contains the WebSocket API, not WebSocket. In simple terms, you can think of WebSocket as HTTP and the WebSocket API as Ajax.

Now let’s use Spring Boot to implement message push using webSocket

1. First we reference the WebSocket dependency that comes with Spring-boot

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Copy the code

2. Write front-end code and process events triggered by background

<script>
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket('ws://localhost:80/websocket');
    }else{
        alert("This browser does not support WebSocket");
    }
 
    websocket.onopen = function (event) {
        console.log("Establish a connection");
    }
 
    websocket.onclose = function (event) {
        console.log("Disconnect");
    }
 
    websocket.onmessage = function (event) {
        console.log("Received a message"+ event.data); / / bounced $('#myModal').modal('show'); // Play music document.getelementById ('notice').play();
    }
 
    websocket.onerror = function (event) {
        alert("Websocket communication error");
    }
 
    window.onbeforeunload = function (event) {
        websocket.close();
    }
</script>
Copy the code

3. Deploy in the Spring container using the WebSocket configuration

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        returnnew ServerEndpointExporter(); }}Copy the code

Note: This Bean will automatically use the Websocket dedPoint declared by the @Serverendpoint annotation. Be aware if you use the Servlet container alone, rather than Spring directly Boot’s built-in container does not need to inject ServerEndpontExporter because it will be provided and managed by the container itself.

4. Write WebSocket concrete implementation classes

@ServerEndpoint(value = "/websocket") @component@slf4j public class MyWebSocket {// A thread-safe Set for a concurrent package, used to store the corresponding MyWebSocket object for each client. private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); // A Session is used to connect to a client and send data to the client. / / @onopen public void OnOpen (Session Session) {this. Session = Session; webSocketSet.add(this); / / to joinsetIn the log. The info ("New connection added! Number of current connections"+ webSocketSet.size()); } /** * connect to close the called method */ @onclose public voidonClose() { webSocketSet.remove(this); / / fromsetRemove the info ("Relational connections, number of current connections"+ webSocketSet.size()); } /** * @param message public void OnMessage (String message, Session session) { log.info("Message from client :"+ message); } @onError public void OnError (Session Session, Throwable error) {log.error("Error occurred"); } /** * Send a message */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); }}Copy the code

Note: The only difference with SpringBoot is that a separate container is used to manage WebSockets under the @Componet declaration, but in SpringBoot even the container is managed by Spring, even though @Componet is singleton by default But SpringBoot still initializes a Bean for each WebSocket Session connection, so it can be stored in a thread-safe Set.

This is an example of a WebSocket message push. Launch your Spring Boot Application and open your HTML file in a different browser to see the WebSocket effect.