SockJS in Spring Boot

SockJS in Spring Boot

In Spring Boot, SockJSis a compatibility solution for implementing WebSocket. This article will introduce SockJSthe principle, usage and sample code of .

insert image description here

What is SockJS

SockJSIt is a communication protocol between the browser and the server, which can establish a two-way communication channel based on HTTP between the browser and the server. SockJSThe main role is to provide a WebSocket compatibility solution, so that browsers that do not support WebSocket can also use WebSocket.

SockJSA WebSocket compatibility layer is implemented, which can establish an HTTP-based communication channel between the browser and the server, and then conduct two-way communication through this channel. When the browser does not support WebSocket, SockJSit will automatically switch to polling or long-polling for communication.

Principle of SockJS

SockJSThe principle of WebSocket is to realize the two-way communication of WebSocket by establishing an HTTP-based communication channel. When the browser supports WebSocket, SockJSit will directly use WebSocket for communication; when the browser does not support WebSocket, SockJSit will automatically switch to polling or long-polling for communication.

When using SockJS, you first need to introduce sockjs-client.jsand on the client side and server side respectively sockjs-server, and then new SockJS(url)establish a SockJSconnection on the client side through .

The communication between the client and the server is event-based, when the client sends a message, the server triggers an onmessageevent and then sends the message back to the client. After the client receives the message, it will trigger an onmessageevent and then process the received message.

How to use SockJS

It is very simple to use SockJS. In Spring Boot, you only need to add the following content to the configuration file:

spring:
  websocket:
    enabled: true
    broker:
      relay-host: localhost
      relay-port: 61613
      user: guest
      password: guest
      relay-path: /stomp

The above configuration indicates that WebSocket is enabled, and messages are sent to the port localhostof 61613, guest/guestthe user name and password of are used for authentication, and /stompthe path of is used for message transmission.

Next, we need to establish a connection in the client SockJSand implement onmessagethe callback method of the event. code show as below:

var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({
    
    }, function(frame) {
    
    
    stompClient.subscribe('/topic/greetings', function(greeting){
    
    
        showGreeting(JSON.parse(greeting.body).content);
    });
});

In the above code, new SockJS('/gs-guide-websocket')it means to use /gs-guide-websocketthe path to establish a SockJSconnection. stompClient.connect({}, function(frame){...})Indicates the callback method executed after the connection is successful, and stompClient.subscribe('/topic/greetings', function(greeting){...})indicates the subscription /topic/greetingsdestination, and the callback method is triggered when a message is published to the destination.

Finally, we need to implement the function of sending and receiving messages on the server side. code show as below:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    
    

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    
    
        registry.enableStompBrokerRelay("/topic")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("guest")
            .setClientPasscode("guest")
            .setSystemHeartbeatSendInterval(5000)
            .setSystemHeartbeatReceiveInterval(4000);
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    
    
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }
}

In the above code, @EnableWebSocketMessageBrokerthe annotation indicates that the WebSocket message broker is enabled, configureMessageBrokerthe method is used to configure the message broker, and registerStompEndpointsthe method is used to register SockJSthe endpoint.

Next, we need to implement the message sending and receiving functions in the controller. code show as below:

@Controller
public class GreetingController {
    
    

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
    
    
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

}

In the above code, @MessageMapping("/hello")the annotation means to process /hellothe message of the destination, and @SendTo("/topic/greetings")the annotation means to send the processing result to /topic/greetingsthe destination. greetingThe method implements the processing logic of the message.

sample code

Here is a complete sample code, including client and server code:

client code

<!DOCTYPE html>
<html>
<head>
    <title>Hello WebSocket</title>
    <script src="/webjars/sockjs-client/1.1.2/dist/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/2.3.3/dist/stomp.min.js"></script>
    <script src="/js/app.js"></script>
</head>
<body>
    <div>
        <label>What is your name?</label>
        <input type="text" id="name" />
        <button type="button" onclick="send()">Send</button>
    </div>
    <div id="greetings">
    </div>
</body>
</html>
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({
    
    }, function(frame) {
    
    
    stompClient.subscribe('/topic/greetings', function(greeting){
    
    
        showGreeting(JSON.parse(greeting.body).content);
    });
});

function send() {
    
    
    var name = document.getElementById('name').value;
    stompClient.send("/app/hello", {
    
    }, JSON.stringify({
    
     'name': name }));
}

function showGreeting(message) {
    
    
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(message));
    document.getElementById('greetings').appendChild(div);
}

server side code

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    
    

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    
    
        registry.enableStompBrokerRelay("/topic")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("guest")
            .setClientPasscode("guest")
            .setSystemHeartbeatSendInterval(5000)
            .setSystemHeartbeatReceiveInterval(4000);
        registry.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    
    
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }
}

@Controller
public class GreetingController {
    
    

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
    
    
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

}

public class HelloMessage {
    
    

    private String name;

    public String getName() {
    
    
        return name;
    }

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

}

public class Greeting {
    
    

    private String content;

    public Greeting(String content) {
    
    
        this.content = content;
    }

    public String getContent() {
    
    
        return content;
    }

}

The above code implements a simple chat room. The user enters his name in the input box, and then clicks the send button to send the message to the server. The server processes the received message and sends it back to the client. received news. When multiple users use the chat room at the same time, each user can see the messages sent by other users.

Summarize

This article introduces the principles in Spring Boot SockJS, includingSockJS

Guess you like

Origin blog.csdn.net/it_xushixiong/article/details/131481874