我用springboot引入websocket,帮我写个完整的后端demo
时间: 2023-07-28 14:52:48 浏览: 91
Springboot+Websocket示例
好的,以下是一个使用Spring Boot和WebSocket的后端示例代码:
1. 首先,在pom.xml文件中添加以下依赖项:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.5.4</version>
</dependency>
</dependencies>
```
2. 创建一个WebSocket配置类,用于配置WebSocket相关的参数:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/my-websocket");
}
}
```
3. 创建一个WebSocket处理程序类,用于处理WebSocket消息:
```java
public class MyWebSocketHandler extends TextWebSocketHandler {
private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
session.sendMessage(new TextMessage("Connected"));
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession s : sessions) {
s.sendMessage(new TextMessage(session.getId() + ": " + message.getPayload()));
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
}
```
4. 运行Spring Boot应用程序,WebSocket服务器将在端口8080上启动。在浏览器中打开两个选项卡,并分别连接到`ws://localhost:8080/my-websocket`。您将看到两个选项卡之间的消息传递。
希望这个示例能够帮助您了解如何使用Spring Boot和WebSocket构建后端应用程序。
阅读全文