SockJS in Spring Boot
In Spring Boot, SockJS
is a compatibility solution for implementing WebSocket. This article will introduce SockJS
the principle, usage and sample code of .
What is SockJS
SockJS
It 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. SockJS
The main role is to provide a WebSocket compatibility solution, so that browsers that do not support WebSocket can also use WebSocket.
SockJS
A 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, SockJS
it will automatically switch to polling or long-polling for communication.
Principle of SockJS
SockJS
The principle of WebSocket is to realize the two-way communication of WebSocket by establishing an HTTP-based communication channel. When the browser supports WebSocket, SockJS
it will directly use WebSocket for communication; when the browser does not support WebSocket, SockJS
it will automatically switch to polling or long-polling for communication.
When using SockJS
, you first need to introduce sockjs-client.js
and on the client side and server side respectively sockjs-server
, and then new SockJS(url)
establish a SockJS
connection 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 onmessage
event and then sends the message back to the client. After the client receives the message, it will trigger an onmessage
event 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 localhost
of 61613
, guest/guest
the user name and password of are used for authentication, and /stomp
the path of is used for message transmission.
Next, we need to establish a connection in the client SockJS
and implement onmessage
the 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-websocket
the path to establish a SockJS
connection. 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/greetings
destination, 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, @EnableWebSocketMessageBroker
the annotation indicates that the WebSocket message broker is enabled, configureMessageBroker
the method is used to configure the message broker, and registerStompEndpoints
the method is used to register SockJS
the 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 /hello
the message of the destination, and @SendTo("/topic/greetings")
the annotation means to send the processing result to /topic/greetings
the destination. greeting
The 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