0%

WebSocket 实现消息推送

传统的 HTTP 协议是请求-响应式的,客户端必须发起请求,服务器才能响应;而 WebSocket 协议则实现了浏览器与服务器全双工通信——允许服务器主动向客户端推送消息;非常适用于聊天应用、实时数据更新、通知系统等场景。

开发使用

引入 WebSocket 依赖

在 Spring Boot 项目中,使用 WebSocket 需要引入 spring-boot-starter-websocket 依赖,Spring Boot 会自动配置 WebSocket 所需的环境。

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置 WebSocket

首先,需要通过 Java 配置类启用 WebSocket 功能。ServerEndpointExporter 是 Spring Boot 中的一个 Bean,它会自动注册所有带有 @ServerEndpoint 注解的类作为 WebSocket 端点。

1
2
3
4
5
6
7
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter createEndPoint() {
return new ServerEndpointExporter();
}
}

创建 WebSocket 服务端点

接下来,我们创建一个服务端点类,用于处理 WebSocket 连接、消息接收和消息发送等操作。通过 @ServerEndpoint 注解,我们指定了 WebSocket 的访问路径。

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
/**
* 让Spring创建WebSocket的服务端点,请求地址为"/ws"
*/
@Service
@ServerEndpoint("/ws")
@Slf4j
public class WebSocketService {
private Session session;

/**
* 客户端打开WebSocket服务端点调用方法
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
log.info("连接建立成功方法调用");
}

/**
* 客户端关闭WebSocket服务端点调用方法
*/
@OnClose
public void onClose() {
log.info("连接关闭方法调用");
}

/**
* 客户端发送消息,WebSocket服务端点调用方法
*
* @param msg 来自客户端的信息
*/
@OnMessage
public void onMessage(String msg) throws IOException {
this.session.getBasicRemote().sendText("服务器端发来的消息啦:你好啊");
log.info("客户端消息:{}", msg);
}
}

创建前端客户端页面

接下来,我们编写一个简单的 HTML 页面,使用 JavaScript 来建立与服务器的 WebSocket 连接,并向服务器发送消息,接收并显示服务器返回的消息。

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
<html>
<title>WebSocket测试页面</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<body>
<input id="message" type="text"/>
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebSocket()">关闭WebSocket连接</button>
<div id="context"></div>
</body>
<script>
let websocket = new WebSocket("ws://localhost:8082/ws");
websocket.onerror = () => {
appendMessage("连接错误")
};

websocket.onopen = () => {
appendMessage("连接成功")
};

//接收消息方法回调
websocket.onmessage = (event) => {
appendMessage(event.data)
};

websocket.onclose = () => {
appendMessage("关闭连接")
};

function appendMessage(message) {
let context = $("#context").html() + "</br>" + message;
$("#context").html(context);
}

//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}

//发送消息
function sendMessage() {
let message = $("#message").val();
websocket.send(message);
}

</script>
</html>