webSocket 是 html5 的一种新协议, 它实现了服务端与客户端的全双工通信, 建立在传输层, tcp 协议之上, 即浏览器与服务端需要先建立 tcp 协议, 再发送 webSocket 连接建立请求. webSocket 的连接: 客户端发送请求信息, 服务端接受到请求并返回相应的信息. 连接建立. 客户端发送 http 请求时, 通过 Upgrade:webSocket Connection:Upgrade 告知服务器需要建立的是 webSocket 连接, 并且还会传递 webSocket 版本号, 协议的字版本号, 原始地址, 主机地址, webSocket 相互通信的 Header 很小, 大概只有 2Bytes
本文介绍 SpringBoot 结合 WebSocket 的实现群发消息, 如想学习如何一对一发送消息可前往查看第二篇 springboot 使用 websocket(二)
1. 导入依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
2. 新建 WebSocket 配置类
- /**
- * @author Gjing
- **/
- @Configuration
- public class WebsocketConfiguration {
- @Bean
- public ServerEndpointExporter serverEndpointExporter() {
- return new ServerEndpointExporter();
- }
- }
3. 新建 WebSocket 服务端
- /**
- * @author Gjing
- **/
- @ServerEndpoint("/test")
- @Component
- @Slf4j
- public class MyWebsocketServer {
- /**
- * 存放所有在线的客户端
- */
- private static Map<String, Session> clients = new ConcurrentHashMap<>();
- @OnOpen
- public void onOpen(Session session) {
- log.info("有新的客户端连接了: {}", session.getId());
- // 将新用户存入在线的组
- clients.put(session.getId(), session);
- }
- /**
- * 客户端关闭
- * @param session session
- */
- @OnClose
- public void onClose(Session session) {
- log.info("有用户断开了, id 为:{}", session.getId());
- // 将掉线的用户移除在线的组里
- clients.remove(session.getId());
- }
- /**
- * 发生错误
- * @param throwable e
- */
- @OnError
- public void onError(Throwable throwable) {
- throwable.printStackTrace();
- }
- /**
- * 收到客户端发来消息
- * @param message 消息对象
- */
- @OnMessage
- public void onMessage(String message) {
- log.info("服务端收到客户端发来的消息: {}", message);
- this.sendAll(message);
- }
- /**
- * 群发消息
- * @param message 消息内容
- */
- private void sendAll(String message) {
- for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
- sessionEntry.getValue().getAsyncRemote().sendText(message);
- }
- }
- }
4. 启动后, 客户端连接 websocket
5. 客户端发送消息得到的响应和服务端的响应
客户端
服务端
以上为简单的使用案例, 更多案例各位可以自行研究, demo 源代码地址: SpringBoot-websocket
来源: https://yq.aliyun.com/articles/706854