帮我写SpringBoot使用WebSocket实现简单的网页一对一聊天功能的代码
时间: 2023-04-02 08:01:26 浏览: 121
好的,我可以回答这个问题。以下是使用SpringBoot实现WebSocket的简单一对一聊天功能的代码示例:
1. 首先,在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建一个WebSocket配置类,用于配置WebSocket相关的参数:
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatWebSocketHandler(), "/chat").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler chatWebSocketHandler() {
return new ChatWebSocketHandler();
}
}
```
3. 创建一个WebSocket处理器类,用于处理WebSocket连接、消息发送等操作:
```
public class ChatWebSocketHandler 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 {
String payload = message.getPayload();
JSONObject jsonObject = JSONObject.parseObject(payload);
String to = jsonObject.getString("to");
String content = jsonObject.getString("content");
WebSocketSession toSession = sessions.get(to);
if (toSession != null && toSession.isOpen()) {
toSession.sendMessage(new TextMessage(content));
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session.getId());
}
}
```
4. 在前端页面中使用JavaScript连接WebSocket,并发送消息:
```
var ws = new WebSocket("ws://localhost:808/chat");
ws.onopen = function() {
console.log("WebSocket连接成功");
};
ws.onmessage = function(event) {
console.log("收到消息:" + event.data);
};
ws.onclose = function() {
console.log("WebSocket连接关闭");
};
function send() {
var to = document.getElementById("to").value;
var content = document.getElementById("content").value;
var message = {
to: to,
content: content
};
ws.send(JSON.stringify(message));
}
```
以上就是使用SpringBoot实现WebSocket的简单一对一聊天功能的代码示例。
阅读全文