SpringMVC的websocket实现一对一聊天
时间: 2023-05-25 16:03:07 浏览: 137
springws:基于SpringMVC实现的WebSocket工程实例
1. 引入相关依赖
在pom.xml文件中引入以下依赖:
```
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
```
2. 配置WebSocket
在SpringMVC配置文件中配置WebSocket:
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatWebSocketHandler(), "/chat");
}
@Bean
public WebSocketHandler chatWebSocketHandler() {
return new ChatWebSocketHandler();
}
}
```
上述代码中,我们通过`@EnableWebSocket`注解启用WebSocket,并通过`registerWebSocketHandlers`方法注册`chatWebSocketHandler`来处理所有连接到`/chat`的WebSocket请求。
3. 创建WebSocketHandler
接下来,创建一个WebSocketHandler类,命名为`ChatWebSocketHandler`:
```
public class ChatWebSocketHandler extends TextWebSocketHandler {
private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String username = session.getPrincipal().getName();
sessionMap.put(username, session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String username = session.getPrincipal().getName();
String recipientUsername = getRecipientUsername(message);
String textMessage = getTextMessage(message);
WebSocketSession recipientSession = sessionMap.get(recipientUsername);
if (recipientSession == null) {
throw new IllegalArgumentException("Recipient " + recipientUsername + " not found");
}
TextMessage text = new TextMessage(username + ": " + textMessage);
recipientSession.sendMessage(text);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
String username = session.getPrincipal().getName();
sessionMap.remove(username);
}
private String getRecipientUsername(WebSocketMessage<?> message) {
String payload = (String) message.getPayload();
return payload.substring(0, payload.indexOf(':'));
}
private String getTextMessage(WebSocketMessage<?> message) {
String payload = (String) message.getPayload();
return payload.substring(payload.indexOf(':') + 2);
}
}
```
上述代码中,我们创建了一个WebSocketHandler类,并重写了`afterConnectionEstablished`、`handleMessage`和`afterConnectionClosed`方法。在`afterConnectionEstablished`方法中,我们将客户端Session保存在一个Map中,以便后续处理时可以根据用户名找到对应的Session;在`handleMessage`方法中,我们从WebSocket消息中获取发送者用户名、接收者用户名和消息内容,并使用接收者用户名获取接收者Session,然后将消息发送给接收者;在`afterConnectionClosed`方法中,我们从Map中删除已经断开连接的Session。
4. 创建WebSocket客户端
最后,创建一个Web页面来展示WebSocket实时通讯效果,代码如下:
```
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<script type="text/javascript">
var socket = new WebSocket("ws://localhost:8080/chat");
socket.onopen = function() {
console.log("WebSocket connection established.");
}
socket.onmessage = function(event) {
console.log(event.data);
var chatMessage = document.createElement("p");
chatMessage.innerText = event.data;
document.getElementById("chat").appendChild(chatMessage);
}
socket.onclose = function(event) {
console.log("WebSocket connection closed (" + event.code + ")");
}
function sendMessage() {
var recipient = document.getElementById("recipient").value;
var message = document.getElementById("message").value;
var payload = recipient + ": " + message;
socket.send(payload);
}
</script>
</head>
<body>
<div id="chat"></div>
<br>
<input type="text" placeholder="Recipient" id="recipient"><br>
<input type="text" placeholder="Message" id="message"><br>
<button onclick="sendMessage()">Send</button>
</body>
</html>
```
上述代码中,我们通过`WebSocket`对象创建了一个WebSocket客户端,并监听了`onopen`、`onmessage`和`onclose`事件。当WebSocket连接成功建立后,会调用`onopen`方法;当收到消息时,会调用`onmessage`方法,在页面上显示收到的消息;当WebSocket连接断开时,会调用`onclose`方法。同时,页面上提供了输入框和发送按钮,点击发送按钮后,会从输入框中获取接收者和消息内容,然后通过WebSocket发送到服务器。
至此,SpringMVC的WebSocket实现一对一聊天就完成了。如果需要群聊功能,只需要稍作修改即可。
阅读全文