springBoot websocket
时间: 2023-11-18 22:53:29 浏览: 106
Spring Boot提供了对WebSocket的支持,可以轻松地实现实时通信功能。在Spring Boot中使用WebSocket需要引入spring-boot-starter-websocket依赖,并且编写WebSocket配置类。
以下是一个简单的Spring Boot WebSocket示例:
1. 引入依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 编写WebSocket配置类
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/my-websocket");
}
}
```
3. 编写WebSocket处理器
```java
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理收到的消息
String payload = message.getPayload();
session.sendMessage(new TextMessage("收到消息:" + payload));
}
}
```
4. 在页面中使用WebSocket
```javascript
var socket = new WebSocket("ws://localhost:8080/my-websocket");
socket.onmessage = function(event) {
console.log("收到消息:" + event.data);
};
socket.send("Hello, WebSocket!");
```
阅读全文