springboot websocket 多人聊天
时间: 2023-12-01 21:43:09 浏览: 86
SpringBoot提供了对WebSocket的支持,可以很方便地实现多人聊天室的功能。具体实现步骤如下:
1.在pom.xml文件中添加WebSocket和Thymeleaf的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2.创建WebSocket配置类,用于注册WebSocket处理器和拦截器:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Autowired
private ChatRoomHandler chatRoomHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatRoomHandler, "/chatRoom")
.addInterceptors(new ChatRoomInterceptor())
.setAllowedOrigins("*");
}
}
```
3.创建WebSocket处理器,用于处理WebSocket连接、消息发送和关闭:
```java
@Component
public class ChatRoomHandler extends TextWebSocketHandler {
private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.put(session.getId(), session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession s : sessions.values()) {
s.sendMessage(message);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session.getId());
}
}
```
4.创建WebSocket拦截器,用于处理用户身份验证等逻辑:
```java
@Component
public class ChatRoomInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
// 处理用户身份验证等逻辑
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
```
5.创建聊天室页面,使用Thymeleaf模板引擎渲染页面,并使用JavaScript代码建立WebSocket连接和发送消息:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Chat Room</title>
<script th:src="@{/webjars/sockjs-client/1.0.2/sockjs.min.js}"></script>
<script th:src="@{/webjars/stomp-websocket/2.3.3/stomp.min.js}"></script>
<script th:inline="javascript">
var stompClient = null;
function connect() {
var socket = new SockJS('/chatRoom');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', function (message) {
showMessage(JSON.parse(message.body));
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
function sendMessage() {
var message = document.getElementById('message').value;
stompClient.send("/app/chat", {}, JSON.stringify({'content': message}));
}
function showMessage(message) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(message.content));
document.getElementById('messages').appendChild(div);
}
</script>
</head>
<body onload="connect()">
<div id="messages"></div>
<input type="text" id="message">
<button onclick="sendMessage()">Send</button>
<button onclick="disconnect()">Disconnect</button>
</body>
</html>
```
6.启动应用程序,访问聊天室页面即可进行多人聊天。
阅读全文