SockJS in Spring Boot
In Spring Boot,SockJS
is a compatibility solution for implementing WebSocket. This article will introduceSockJS
principle, usage method and sample code.
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 function is to provide a compatibility solution for WebSocket, so that browsers that do not support WebSocket can also use WebSocket.
SockJS
Implements 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,SockJS
It will automatically switch to using polling or long-polling for communication.
The principle of SockJS
SockJS
The principle is to realize two-way communication of WebSocket by establishing an HTTP-based communication channel. When the browser supports WebSocket,SockJS
It will use WebSocket directly to communicate; when the browser does not support WebSocket,SockJS
It will automatically switch to using polling or long-polling for communication.
In useSockJS
When it comes to the client and server, it is necessary to introduce it separatelyand
sockjs-server
, then pass on the clientnew SockJS(url)
Create aSockJS
connect.
The communication between the client and the server is event-based. When the client sends a message, the server will trigger aonmessage
event, and then send the message back to the client. After the client receives the message, it will trigger aonmessage
Events, and then process the received message.
How to use SockJS
useSockJS
It'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 tolocalhost
of61613
Port, useguest/guest
Username and password are authenticated and used/stomp
The path performs message transmission.
Next, we need to create aSockJS
Connect and implementonmessage
Callback 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-websocket
Create a pathSockJS
connect.({}, function(frame){...})
Indicates the callback method executed after the connection is successful.('/topic/greetings', function(greeting){...})
Indicates a subscription/topic/greetings
Destination, 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,@EnableWebSocketMessageBroker
Annotation means enabling the WebSocket message broker.configureMessageBroker
Methods are used to configure the message broker,registerStompEndpoints
Method for registrationSockJS
Endpoint.
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/hello
Destination news,@SendTo("/topic/greetings")
Annotation means sending the processing result to/topic/greetings
destination.greeting
The 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
,includeSockJS
Principles, 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!