曹耘豪的博客

Spring Boot使用WebSocket实现聊天功能

  1. Spring Boot后端
    1. 引入依赖
    2. 增加Configuration
    3. 增加业务处理代码
  2. 前端
  3. 运行

Spring Boot后端

引入依赖

1
2
3
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-websocket'
}

增加Configuration

WebSocketConfiguration.java
1
2
3
4
5
6
7
8
9
@Configuration
public class WebSocketConfiguration {

@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}

}

增加业务处理代码

WebSocketServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Slf4j
@Component
@ServerEndpoint("/websocket/chat/from/{from}/to/{to}")
public class WebSocketServer {

private static final Map<Integer, Session> sessionMap = new ConcurrentHashMap<>();

@OnOpen
public void onOpen(Session session, @PathParam("from") Integer from) {
log.info("accept connection userId={}", from);
sessionMap.put(from, session);
}

@SneakyThrows
@OnClose
public void onClose(@PathParam("from") Integer from) {
log.info("close connection userId={}", from);
sessionMap.remove(from);
}

@OnMessage
public void onMessage(String message, @PathParam("from") Integer from, @PathParam("to") Integer to) {
log.info("Receive {} from userId={} to {}", message, from, to);

Session session = sessionMap.get(to);
session.getAsyncRemote().sendText(message);
}

@OnError
public void onError(Session session, Throwable error) {
log.error("error", error);
}


}

前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8"/>
<metaname="viewport"content="width=device-width, initial-scale=1.0"/>
<title>WebSocket 发送普通文本示例</title>
</head>
<body>
<h3>WebSocket 发送普通文本示例</h3>
<div>
<div class="block">
<p>发送内容:</p>
<textarea id="sendMessage"></textarea><span><button onclick="send()">发送</button></span>
</div>
<div class="block">
<p>接收内容:</p>
<textarea id="receivedMessage"></textarea>
</div>
</div>
<script>
var searchParams = new URLSearchParams(window.location.search);
console.log(searchParams)
var from = searchParams.get("from")
var to = searchParams.get("to")

const sendMsgContainer = document.querySelector("#sendMessage");
const receivedMsgContainer = document.querySelector("#receivedMessage");
const socket = new WebSocket(`ws://127.0.0.1:8080/websocket/chat/from/${from}/to/${to}`);

socket.addEventListener("open", function (event) {
alert("连接成功,可以开始通讯");
});

socket.addEventListener("message", function (event) {
console.log("Receive:", event.data);
receivedMsgContainer.value = event.data;
});

function send() {
const message = sendMsgContainer.value;
if (socket.readyState !== WebSocket.OPEN) {
alert("连接未建立,还不能发送消息");
return;
}
if (message) {
console.log("Send:", message);
socket.send(message);
}
}
</script>
</body>
</html>

运行

  1. 运行后端Spring Boot程序
  2. 打开两次网页,添加参数?from=1&to=2?from=2&to=1,添加后刷新页面即可连接成功
  3. 开始对话
   /