Implementing the WebSocket service in Spring Boot and allowing clients to receive messages in real time can use the built-in WebSocket support in Spring Boot. Below I provide you with a complete demo based on Spring Boot and WebSocket.
1. Introduce dependencies
First, inAdd the dependencies of WebSocket in:
<dependencies> <!-- WebSocket rely --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> </dependencies>
2. WebSocket configuration
Create a configuration class, used to configure the endpoint and processing logic of WebSocket.
import ; import ; import ; import ; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // Register WebSocket processors and endpoints (new WebSocketHandler(), "/websocket") .setAllowedOrigins("*"); // Allow cross-domain } }
3. WebSocket Processor
Create, handles WebSocket connection, message reception, message broadcast and other operations.
import ; import ; import ; import ; import ; import ; public class WebSocketHandler extends TextWebSocketHandler { // Used to save all connected WebSocket sessions private static final Set<WebSocketSession> sessions = new HashSet<>(); // Called when there is a client connection @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { (session); (new TextMessage("Welcome to connect to the WebSocket server!")); } // Called when a message is sent from the client @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { ("Received the client message: " + ()); } // Called when the connection is closed @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { (session); } // Broadcast messages to all connected clients public static void broadcast(String message) throws Exception { for (WebSocketSession session : sessions) { if (()) { (new TextMessage(message)); } } } }
4. Simulation announcement push
Create a controller, simulate the release function of announcements. When an announcement is issued, the WebSocket processor will be called.
broadcast
Method, push messages to all connected clients.
import ; import ; @RestController public class AnnouncementController { @GetMapping("/announce") public String sendAnnouncement() { try { // Simulation announcement content String announcement = "New announcement is published: " + (); (announcement); return "Announcement has been issued: " + announcement; } catch (Exception e) { (); return "Release failed"; } } }
5. Running steps
1. Start Spring Boot application
After starting the Spring Boot project, the WebSocket server will be in/websocket
Listen on the endpoint.
2. Mini program or web client
The client can be a mini program or a web page. Here is a simple HTML client to test WebSocket connections.
HTML client code (for testing WebSocket connections):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Demo</title> </head> <body> <h1>WebSocket Demo</h1> <div ></div> <script> // Connect to WebSocket Server var socket = new WebSocket("ws://localhost:8080/websocket"); = function() { ("The connection was successful!"); }; = function(event) { ("Message received:", ); ("messages").innerHTML += "<p>" + + "</p>"; }; = function() { ("Connection closed!"); }; </script> </body> </html>
3. Issuing an announcement
Access using a browserhttp://localhost:8080/announce
, Each time you access this address, the server pushes an announcement message to all connected WebSocket clients.
6. Mini-program implementation
You can also use a similar method in WeChat applets to receive announcements pushed by the server through WebSocket.
Page({ data: { messages: [] // Save the received announcement message }, onLoad: function() { // Connect to WebSocket Server ({ url: 'ws://localhost:8080/websocket', // Please modify it to your server address success: (res) => { ('WebSocket connection is successful! '); }, fail: (err) => { ('WebSocket connection failed', err); } }); // Listen to WebSocket messages ((res) => { ('Received the server message:', ); ({ messages: [..., ] // Add new messages to the list }); }); // Listen to WebSocket connection closed ((res) => { ('WebSocket closed', res); }); } });
7. Summary
- Through Spring Boot's WebSocket support, real-time announcements can be pushed on the server side.
- The client can be an HTML page or a WeChat applet, and it can use the WebSocket interface to receive announcement messages.
This is the article about SpringBoot implementing WebSocket service and allowing clients to receive real-time. For more relevant SpringBoot WebSocket content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!