preface

SpringBoot implements WebSocket broadcast messages.

What is WebSocket?

WebSocket provides duplex asynchronous communication between the browser and the server, meaning that the browser can send messages to the server and vice versa.

WebSocket implements duplex asynchronous communication capability through a socket, but directly uses WebSocket (or SockJS: Emulated the WebSocket protocol, adding compatible support for using WebSocket that is not supported by current browsers.) Protocol development is cumbersome, so use its subprotocol STOMP.

STOMP Protocol Overview

It is an advanced streaming text-directed messaging protocol, a simple text protocol designed for MOM (Message Oriented Middleware).

It provides an interoperable connection format that allows STOMP clients to interact with any STOMP message Broker, similar to OpenWire (a binary protocol).

Because of its simple design and easy client development, it is widely used in many languages and many platforms. One of the most popular STOMP message brokers is Apache ActiveMQ.

STOMP uses a (frame) -based format to define messages, similar to Http request and Response.

radio

Next, implement a demo of broadcast messages. That is, when the server has a message, it sends the message to all browsers connected to the current endpoint.

The preparatory work

  • SpringBoot 2.1.3
  • IDEA
  • JDK8

Pom dependency configuration

<dependencies>
        <! Thymeleaf template engine -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <! -- Web startup class -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <! -- WebSocket dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <! -- test unit test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
Copy the code

The code comments are more detailed than that.

Configure the WebSocket

Implement WebSocketMessageBrokerConfigurer interface, registered a STOMP node, equipped with a radio message broker

@Configuration
/ / @ EnableWebSocketMessageBroker annotations for open use STOMP protocol to transmit messages based on agent (MessageBroker), then the controller (the controller)
// Start supporting @messagemapping like @requestMapping.
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // Register a Stomp node (endpoint) and specify the use of the SockJS protocol.
        registry.addEndpoint("/endpointNasus").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // The broadcast configuration is called /nasus message broker, which must match or match the address prefix configured by @sendto in controller
        registry.enableSimpleBroker("/nasus"); }}Copy the code

The message classes

The client sends to the server:

public class Client2ServerMessage {

    private String name;

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

The server sends to the client:

public class Server2ClientMessage {

    private String responseMessage;

    public Server2ClientMessage(String responseMessage) {
        this.responseMessage = responseMessage;
    }

    public String getResponseMessage(a) {
        return responseMessage;
    }

    public void setResponseMessage(String responseMessage) {
        this.responseMessage = responseMessage; }}Copy the code

Demo controller code

@RestController
public class WebSocketController {

    @MessageMapping("/hello") @messagemapping is similar to @requestMapping. The browser sends a message to the server and maps the message to the address.
    @SendTo("/nasus/getResponse") // If the server receives the message, it will send it to the browser that subscribed to the address in parentheses @sendto.
    public Server2ClientMessage say(Client2ServerMessage message) throws Exception {
        Thread.sleep(3000);
        return new Server2ClientMessage("Hello," + message.getName() + "!"); }}Copy the code

Introduce STOMP scripts

Put stomp.min.js (stomp client script) and sockjs.min. js (sockJS client script) and Jquery in the static directory of the Resource folder.

The demo page


      
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Spring Boot+WebSocket+ broadcast</title>

</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">It appears that your browser does not support Websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">The connection</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">disconnect</button>
    </div>
    <div id="conversationDiv">
        <label>Enter your name</label><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">send</button>
        <p id="response"></p>
    </div>
</div>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = ! connected;document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }
	
    function connect() {
        // The endpoint name to connect to SockJs is "/endpointNasus"
        var socket = new SockJS('/endpointNasus'); 
        // WebSocket client using STOMP subprotocol
        stompClient = Stomp.over(socket); 
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            // Message sent via stompClient.subscribe /nasus/getResponse target, corresponding to controller SendTo definition
            stompClient.subscribe('/nasus/getResponse'.function(respnose){
            If you subscribe to the /nasus/getResponse target, you can receive the message returned by the server
            showResponse(JSON.parse(respnose.body).responseMessage);
            });
        });
    }
	
	
    function disconnect() {
        // Disconnect the connection
        if(stompClient ! =null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        // Send a message to the server
        var name = $('#name').val();
        // Send a message to/Hello (server) via stompClient.send, as defined in controller @messagemapping
        stompClient.send("/hello", {}, JSON.stringify({ 'name': name }));
    }

    function showResponse(message) {
          // Receive the returned message
          var response = $("#response");
          response.html(message);
    }
</script>
</body>
</html>
Copy the code

Page Controller

Notice that the @Controller annotation is used to match the HTML prefix and load the page.

@Controller
public class ViewController {

    @GetMapping("/nasus")
    public String getView(a){
        return "nasus"; }}Copy the code

The test results

Three Windows open access http://localhost:8080/nasus, initial page long like this:

Click connect on all three pages and click Connect to subscribe to the endpoint, as shown below:

On the first page, enter your name and click Send, as shown below:

Send a message on the first page and wait for 3 seconds. The result is that all three pages receive the message returned by the server, and the broadcast is successful.

Source code download:

https://github.com/turoDog/Demo/tree/master/springboot_websocket_demo

If you think it is helpful, please give a Star and then go. Thank you very much.

After the language

If this article is of any help to you, please help to read it. Your good looks are my motivation to keep writing.

In addition, after paying attention to send 1024 can receive free learning materials.

For more information, see this article: Python, C++, Java, Linux, Go, front-end, algorithm sharing