帮我写一个用SpringBoot集成websocket的实例
时间: 2024-06-11 16:07:29 浏览: 157
好的,下面是一个用SpringBoot集成websocket的实例:
1. 创建一个SpringBoot项目,添加以下依赖:
```xml
<!-- SpringBoot Websocket依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建一个WebSocketConfig类,用于配置WebSocket相关的信息:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/my-websocket")
.setAllowedOrigins("*");
}
}
```
3. 创建一个WebSocketHandler类,用于处理WebSocket连接的请求和响应:
```java
@Component
public class MyWebSocketHandler extends TextWebSocketHandler {
private final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
super.afterConnectionClosed(session, status);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession webSocketSession : sessions) {
if (webSocketSession.isOpen()) {
webSocketSession.sendMessage(message);
}
}
}
}
```
4. 创建一个IndexController类,用于处理WebSocket连接的页面请求:
```java
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}
```
5. 创建一个index.html页面,用于测试WebSocket连接:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<div id="messages"></div>
<form>
<input type="text" id="message" />
<button type="button" onclick="sendMessage()">Send</button>
</form>
<script>
var webSocket = new WebSocket("ws://localhost:8080/my-websocket");
webSocket.onmessage = function(event) {
var message = event.data;
$("#messages").append("<p>" + message + "</p>");
};
function sendMessage() {
var message = $("#message").val();
webSocket.send(message);
}
</script>
</body>
</html>
```
6. 运行SpringBoot应用,访问http://localhost:8080/,即可测试WebSocket连接。
以上就是一个用SpringBoot集成WebSocket的实例。
阅读全文