springboot websocket 怎么写,包括API请求示例
时间: 2023-07-01 10:24:50 浏览: 89
Spring Boot提供了对WebSocket的支持,可以轻松地实现WebSocket应用程序。下面是一个简单的Spring Boot WebSocket示例:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 编写WebSocket处理器
创建一个类,实现`WebSocketHandler`接口来处理WebSocket连接和消息。例如:
```java
@Component
public class MyWebSocketHandler implements WebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 连接建立后的处理逻辑
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
// 处理收到的消息
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
// 连接错误处理逻辑
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
// 连接关闭处理逻辑
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
```
3. 配置WebSocket
在`WebSocketConfig`中配置WebSocket。例如:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private MyWebSocketHandler myWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler, "/myWebSocketHandler");
}
}
```
4. 发送WebSocket消息
在控制器中注入`SimipMessagingTemplate`,使用`convertAndSend`方法发送WebSocket消息。例如:
```java
@RestController
public class WebSocketController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@GetMapping("/sendMessage")
public void sendMessage() {
messagingTemplate.convertAndSend("/myWebSocketHandler", "Hello, WebSocket!");
}
}
```
5. 发送API请求
使用浏览器或者WebSocket客户端发送WebSocket请求。例如,在浏览器中使用JavaScript可以这样发送WebSocket请求:
```javascript
var socket = new WebSocket("ws://localhost:8080/myWebSocketHandler");
socket.onmessage = function(event) {
console.log(event.data);
}
socket.send("Hello, WebSocket!");
```
这就是一个简单的Spring Boot WebSocket示例,你可以根据需求进行修改和扩展。
阅读全文