在springboot中使用websocket
时间: 2023-10-24 11:08:05 浏览: 94
springboot+websocket分布式实现
在Spring Boot中使用WebSocket需要进行以下步骤:
1. 引入WebSocket依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建WebSocket处理器
```java
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理收到的消息
String payload = message.getPayload();
// 发送消息给所有连接的客户端
session.getWebSocketHandler().broadcast(new TextMessage("Hello, " + payload + "!"));
}
}
```
3. 配置WebSocket
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler(), "/my-websocket").setAllowedOrigins("*");
}
@Bean
public MyWebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
}
```
4. 编写前端代码
```html
<script>
var socket = new WebSocket("ws://localhost:8080/my-websocket");
socket.onmessage = function(event) {
// 处理收到的消息
console.log(event.data);
}
socket.send("World");
</script>
```
以上就是在Spring Boot中使用WebSocket的步骤,你可以根据自己的实际情况进行调整。
阅读全文