欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 使用 Spring Boot 搭建 WebSocket 服务器实现多客户端连接

使用 Spring Boot 搭建 WebSocket 服务器实现多客户端连接

2025/4/22 21:11:39 来源:https://blog.csdn.net/lps12345666/article/details/143393343  浏览:    关键词:使用 Spring Boot 搭建 WebSocket 服务器实现多客户端连接

在 Web 开发中,WebSocket 为客户端和服务端之间提供了实时双向通信的能力。本篇博客介绍如何使用 Spring Boot 快速搭建一个 WebSocket 服务器,并支持多客户端的连接和消息广播。

1. WebSocket 简介

WebSocket 是 HTML5 的一种协议,提供了客户端和服务器之间的全双工通信。通过 WebSocket,客户端可以与服务器进行持续连接,不用反复建立 HTTP 请求,从而降低延迟,提升通信效率。

为什么选择 Spring Boot 实现 WebSocket?

Spring Boot 简化了 WebSocket 服务器的配置与实现,使我们可以更专注于业务逻辑开发,且配合 @ServerEndpoint 注解实现更加清晰。

2. 项目环境与依赖配置

项目环境

  • Java 版本:JDK 8+
  • Spring Boot 版本:2.x
  • WebSocket 依赖spring-boot-starter-websocket

Maven 依赖

pom.xml 文件中添加 WebSocket 的依赖:

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

3. WebSocket 服务端代码实现

在 Spring Boot 中,我们可以使用 @ServerEndpoint 注解创建 WebSocket 服务器端。以下是一个支持多客户端连接的 WebSocket 实现。

WebSocket 服务端代码解析

创建 MultiClientWebSocket 类,并实现以下功能:

  1. 记录当前在线客户端数
  2. 支持客户端连接、断开、消息接收、群发等功能
  3. 通过 @OnOpen@OnMessage@OnClose@OnError 注解处理连接的各个生命周期

完整代码如下:

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;/*** WebSocketConfig*/
@Component
@ServerEndpoint("/ws/multi")
@Slf4j
public class MultiClientWebSocket {@Beanpublic ServerEndpointExporter serverEndpointExporter() {log.info("WebSocketConfig: serverEndpointExporter init WebSocketConfig 注入完成");return new ServerEndpointExporter();}/*** 记录当前在线连接数*/private static final AtomicInteger onlineCount = new AtomicInteger(0);/*** 存放所有在线的客户端*/private static final Map<String, Session> onlineClients = new ConcurrentHashMap<>();@OnOpenpublic void onOpen(Session session) {onlineCount.incrementAndGet();onlineClients.put(session.getId(), session);log.info("有新连接加入:{},当前在线客户端数为:{}", session.getId(), onlineCount.get());}@OnMessagepublic void onMessage(String message, Session session) throws IOException {System.out.println("收到客户端消息:" + message);session.getBasicRemote().sendText("服务器收到消息:" + message);}@OnClosepublic void onClose(Session session) {onlineCount.decrementAndGet(); // 在线数减1onlineClients.remove(session.getId());log.info("有一连接关闭:{},当前在线客户端数为:{}", session.getId(), onlineCount.get());}@OnErrorpublic void onError(Throwable t) {log.error("WebSocket 连接出错{}", t.getMessage());}/*** 群发消息** @param message 消息内容*/public void sendMessage(String message) {//log.info("开始给在线的客户端{}群发消息{}",onlineClients,message);for (Map.Entry<String, Session> sessionEntry : onlineClients.entrySet()) {Session toSession = sessionEntry.getValue();log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);toSession.getAsyncRemote().sendText(message);}}}

代码解析

  • ServerEndpointExporter:Spring Boot 的 WebSocket 配置类,自动注册 @ServerEndpoint 注解声明的 WebSocket。
  • 在线客户端管理:使用 ConcurrentHashMap 存储在线客户端的 Session,通过 AtomicInteger 记录当前连接数。
  • 生命周期注解
    • @OnOpen:当客户端连接时触发,增加在线人数。
    • @OnMessage:当收到消息时触发,服务端处理消息。
    • @OnClose:当连接关闭时触发,减少在线人数。
    • @OnError:当连接出错时触发,记录错误日志。
  • 群发消息sendMessage 方法遍历所有在线客户端的 Session,实现消息广播。

4. 启动与测试

启动 Spring Boot 项目后,WebSocket 服务端地址为:ws://localhost:8080/ws/multi。可以使用 WebSocket 测试工具(例如 Apifox或浏览器控制台)测试 WebSocket 通信。

测试步骤

  1. 连接 WebSocket:客户端连接至 ws://localhost:8080/ws/multi
  2. 发送消息:客户端发送消息,服务端接收到消息后回复。
  3. 断开连接:客户端断开连接,服务端记录连接关闭信息。
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Lists;
import com.lps.config.MultiClientWebSocket;
import com.lps.domain.R;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @ClassName: WebSocketControl* @Description:* @Author: liu* @Date: 2024-10-30* @Version: 1.0**/
@RestController
@RequestMapping("/webSocket")
@RequiredArgsConstructor
public class WebSocketControl {private final MultiClientWebSocket multiClientWebSocket;@GetMapping("/sendList")public R<String> sad() {//Guava依赖List<String> strList = Lists.newArrayList("发送", "WebSocket消息","测试");String jsonStr = JSONUtil.toJsonStr(strList);multiClientWebSocket.sendMessage(jsonStr);return R.ok(jsonStr);}
}

前端测试demo

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>WebSocket Demo</title><style>#status {margin-bottom: 10px;}</style><script>let ws;function connectWebSocket() {// 检查 WebSocket 是否已连接if (ws && ws.readyState === WebSocket.OPEN) {console.log('WebSocket 已连接,无需重复连接。');return;}ws = new WebSocket('ws://localhost:8080/ws/multi');ws.onopen = function() {console.log('WebSocket 连接已经建立。');document.getElementById('status').innerText = 'WebSocket 连接已建立。';ws.send('Hello, server!');};ws.onmessage = function(event) {console.log('收到服务器消息:', event.data);document.getElementById('messages').innerText += '收到消息:' + event.data + '\n';};ws.onerror = function(event) {console.error('WebSocket 连接出现错误:', event);document.getElementById('status').innerText = 'WebSocket 连接出现错误。';};ws.onclose = function() {console.log('WebSocket 连接已经关闭。');document.getElementById('status').innerText = 'WebSocket 连接已关闭。';ws = null; // 连接关闭后将 ws 设置为 null,以便重新连接};}function disconnectWebSocket() {if (ws) {ws.close();}}</script>
</head>
<body><h1>WebSocket Demo</h1><div id="status">WebSocket 连接状态</div><button onclick="connectWebSocket()">连接 WebSocket</button><button onclick="disconnectWebSocket()">断开 WebSocket</button><pre id="messages"></pre>
</body>
</html>

5. 总结

通过以上代码示例,我们可以实现一个简单的 WebSocket 服务端,支持多客户端连接和消息广播。此 WebSocket 服务端适用于需要实时消息推送的应用场景,比如聊天室、实时通知系统等。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词