SoFunction
Updated on 2025-03-08

The principle and usage method of SockJS in Spring Boot

SockJS in Spring Boot

In Spring Boot,SockJSis a compatibility solution for implementing WebSocket. This article will introduceSockJSprinciple, usage method and sample code.

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 function is to provide a compatibility solution for WebSocket, so that browsers that do not support WebSocket can also use WebSocket.

SockJSImplements a compatibility layer of WebSocket, which can establish an HTTP-based communication channel between the browser and the server, and then communicate in two-way through this channel. When the browser does not support WebSocket,SockJSIt will automatically switch to using polling or long-polling for communication.

The principle of SockJS

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

In useSockJSWhen it comes to the client and server, it is necessary to introduce it separatelyandsockjs-server, then pass on the clientnew SockJS(url)Create aSockJSconnect.

The communication between the client and the server is event-based. When the client sends a message, the server will trigger aonmessageevent, and then send the message back to the client. After the client receives the message, it will trigger aonmessageEvents, and then process the received message.

How to use SockJS

useSockJSIt's very simple. In Spring Boot, you just need to add the following 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 means enabling WebSocket and sending messages tolocalhostof61613Port, useguest/guestUsername and password are authenticated and used/stompThe path performs message transmission.

Next, we need to create aSockJSConnect and implementonmessageCallback method for events. The code is as follows:

var socket = new SockJS('/gs-guide-websocket');
stompClient = (socket);
({}, function(frame) {
    ('/topic/greetings', function(greeting){
        showGreeting(().content);
    });
});

In the above code,new SockJS('/gs-guide-websocket')Indicates use/gs-guide-websocketCreate a pathSockJSconnect.({}, function(frame){...})Indicates the callback method executed after the connection is successful.('/topic/greetings', function(greeting){...})Indicates a subscription/topic/greetingsDestination, triggers callback method when a message is posted to the destination.

Finally, we need to implement the functions of message sending and receiving on the server side. The code is as follows:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        ("/topic")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("guest")
            .setClientPasscode("guest")
            .setSystemHeartbeatSendInterval(5000)
            .setSystemHeartbeatReceiveInterval(4000);
        ("/app");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        ("/gs-guide-websocket").withSockJS();
    }
}

In the above code,@EnableWebSocketMessageBrokerAnnotation means enabling the WebSocket message broker.configureMessageBrokerMethods are used to configure the message broker,registerStompEndpointsMethod for registrationSockJSEndpoint.

Next, we need to implement the functions of sending and receiving messages in the controller. The code is as follows:

@Controller
public class GreetingController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        (1000); // simulated delay
        return new Greeting("Hello, " + (()) + "!");
    }
}

In the above code,@MessageMapping("/hello")Annotation representation processing/helloDestination news,@SendTo("/topic/greetings")Annotation means sending the processing result to/topic/greetingsdestination.greetingThe method implements the message processing logic.

Sample code

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

Client Code

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

Server-side code

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        ("/topic")
            .setRelayHost("localhost")
            .setRelayPort(61613)
            .setClientLogin("guest")
            .setClientPasscode("guest")
            .setSystemHeartbeatSendInterval(5000)
            .setSystemHeartbeatReceiveInterval(4000);
        ("/app");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        ("/gs-guide-websocket").withSockJS();
    }
}
@Controller
public class GreetingController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        (1000); // simulated delay
        return new Greeting("Hello, " + (()) + "!");
    }
}
public class HelloMessage {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
}
public class Greeting {
    private String content;
    public Greeting(String content) {
         = content;
    }
    public String getContent() {
        return content;
    }
}

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

Summarize

This article introduces theSockJS,includeSockJSPrinciples, usage methods and example codes

This is all about this article about SockJS in Spring Boot. For more related Spring Boot SockJS content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!