In modern web application development, WebSocket is a common technology for instant communication and real-time data transmission. The Spring Boot framework provides support for integrated WebSocket, making it very convenient for developers to implement push and notification functions.
This article will introduce how to use WebSocket to implement push and notification functions in Spring Boot, and demonstrate the implementation of a simple real-time online chat room.
First, we need to create a Spring Boot project. You can quickly create a new project using the web and WebSocket dependencies on the Spring Initializr website. The code is as follows:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> </dependencies>
Next, we need to configure WebSocket so that it can run in a Spring Boot application.
First, we need to add the following attributes to the application configuration file:
spring.websocket.enabled=true
Then, add a @EnableWebSocket
annotation to the Spring Boot configuration class to enable WebSocket support. At the same time, we need to implement a WebSocketConfigurer
interface and register handlers and message interceptors in it to process WebSocket requests and messages.
The code is as follows:
@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new WebSocketHandler(), "/chat").setAllowedOrigins("*").withSockJS(); } }
In the above code, we registered a handler (i.e. WebSocketHandler) that is called when the client connects to the "/chat" endpoint. Use the setAllowedOrigins
method to specify allowed origins for cross-origin requests, and the withSockJS
method to enable SockJS support for compatibility with browsers that do not support WebSocket.
Now we need to write a handler class, which will handle all WebSocket requests and messages.
In Spring Boot, this class only needs to implement the WebSocketHandler
interface. We will use the SimpeTextWebSocketHandler
class, which provides basic functionality for processing WebSocket messages, and we can extend our own handlers based on it.
The code is as follows:
public class WebSocketHandler extends TextWebSocketHandler { private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { sessions.remove(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession s : sessions) { if (s.isOpen() && !s.equals(session)) { s.sendMessage(message); } } } }
In the above code, the afterConnectionEstablished
method is called when a new WebSocket session is established, and the afterConnectionClosed
method is called when a new WebSocket session is established. Called when the session is closed. The handleTextMessage
method handles all WebSocket messages and sends them to all currently connected clients.
Now, we need to create a WebSocket client to test the implemented push and notification functionality. You can use JavaScript's WebSocket API to create a WebSocket client.
The code is as follows:
const socket = new WebSocket('ws://localhost:8080/chat'); socket.onopen = function() { console.log('连接已建立'); }; socket.onmessage = function(event) { console.log('收到消息:', event.data); }; socket.onerror = function(error) { console.log('发生错误:', error); }; socket.onclose = function() { console.log('连接已关闭'); };
In the above code, we create a WebSocket instance and try to connect to ws://localhost:8080/chat
. We then listen to WebSocket events for open, close, error and message events.
Now we can start the Spring Boot application and test the push and notification functionality. We can use two or more WebSocket clients to impersonate different users and enter messages in one client and broadcast them to other clients in all sessions.
Use Maven to run the spring-boot:run
command to start the application.
Now, open multiple browser windows and create a WebSocket client in each window. Enter your message and hit the send button to push the message to other WebSocket clients in all sessions you are chatting with.
In this tutorial, we have learned how to use Spring Boot and WebSocket to implement push and notification functions. With WebSocket support, we can create real-time, collaborative, and multicast applications that enhance the user experience and increase the value of the application.
The above is the detailed content of Using WebSocket in Spring Boot to implement push and notification functions. For more information, please follow other related articles on the PHP Chinese website!