springboot 如何使用WebSocket
时间: 2024-03-23 13:41:48 浏览: 56
要在Spring Boot中使用WebSocket,需要进行以下步骤:
1. 添加Spring Boot WebSocket依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建WebSocket配置
创建一个WebSocket配置类,该类需要继承WebSocketConfigurer,并实现registerWebSocketHandlers方法。
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/myWebSocketHandler").setAllowedOrigins("*");
}
}
```
3. 创建WebSocket处理程序
创建一个WebSocket处理程序,继承TextWebSocketHandler,并重写handleTextMessage方法。
```
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的消息
String payload = message.getPayload();
// 发送消息
session.sendMessage(new TextMessage("Received message: " + payload));
}
}
```
4. 将WebSocket集成到Spring Boot应用程序
在Spring Boot应用程序中使用WebSocket,可以使用@MessageMapping和@SendTo注释,例如:
```
@Controller
public class MyController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(String message) throws Exception {
return new Greeting("Hello, " + message + "!");
}
}
```
5. 测试WebSocket
可以使用浏览器中的JavaScript WebSocket API测试WebSocket。例如:
```
var socket = new WebSocket("ws://localhost:8080/myWebSocketHandler");
socket.onmessage = function(event) {
console.log("Received message: " + event.data);
};
socket.send("Hello, WebSocket!");
```
阅读全文