用springboot做一个websocket的测试demo
时间: 2023-07-18 18:03:22 浏览: 105
好的,以下是一个简单的Spring Boot WebSocket测试Demo:
1. 创建一个新的Spring Boot项目,添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</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处理器类:
```java
public class MyWebSocketHandler extends TextWebSocketHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocketHandler.class);
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
LOGGER.info("Connection established: " + session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
LOGGER.info("Message received: " + message.getPayload());
session.sendMessage(new TextMessage("Response: " + message.getPayload()));
}
}
```
4. 创建一个WebSocket客户端类,用于测试WebSocket连接:
```java
public class MyWebSocketClient extends WebSocketHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocketClient.class);
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
LOGGER.info("Connection established: " + session.getId());
session.sendMessage(new TextMessage("Hello, server!"));
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
LOGGER.info("Message received: " + message.getPayload());
}
}
```
5. 添加一个测试Controller,用于打开WebSocket连接:
```java
@RestController
public class TestController {
private WebSocketHandler handler = new MyWebSocketClient();
@GetMapping("/test-websocket")
public String testWebSocket() throws Exception {
WebSocketClient client = new StandardWebSocketClient();
WebSocketSession session = client.doHandshake(handler, "ws://localhost:8080/my-websocket").get();
session.sendMessage(new TextMessage("Hello, server!"));
Thread.sleep(5000);
session.close();
return "WebSocket test successful!";
}
}
```
6. 运行应用程序,并访问 http://localhost:8080/test-websocket 进行测试。
以上是一个简单的Spring Boot WebSocket测试Demo,你可以根据自己的需求进行修改和扩展。
阅读全文