简介:WebSocket是基于TCP的网络协议,它实现了服务器可以主动发送消息给客户端,当然客户端也可以给服务器发送消息。HTTP协议缺陷是通讯只能由客户端发起,以前获取消息时,是前端采用轮询方式向后端请求获取数据,这样效率低,且浪费资源,WebSocket由此诞生。
1. pom.xml Maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. WebSocketConfig配置类
package com.ruhaunxingyun.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @description: 开启WebSocket * @author: ruphie * @date: Create in 2020/3/25 14:36 * @company: ruhuanxingyun */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
3. WebSocketServer核心类
package com.ruhuanxingyun.websocket; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * @description: 发送与接收消息 * @author: ruphie * @date: Create in 2020/3/27 10:33 * @company: ruhuanxingyun */ @Component @ServerEndpoint("/ws/ruhuanxingyun/{userId}") @Slf4j public class WebSocketServer { private static AtomicInteger onlineNum = new AtomicInteger(); private static Map<Long, Session> map = new ConcurrentHashMap<>(); /** * 建立连接 * * @param session session * @param userId 用户ID */ @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) { int num = onlineNum.incrementAndGet(); map.put(Long.valueOf(userId), session); log.info("新建立客户端连接,sessionId为:{},当前连接数为:{}", session.getId(), num); } /** * 关闭连接 * * @param session session */ @OnClose public void onClose(Session session) { map.values().remove(session); int num = onlineNum.decrementAndGet(); log.info("sessionId为{}的客户端连接关闭,当前剩余连接数为:{}", session.getId(), num); } /** * 客户端发送消息 * * @param session session * @param message 消息 */ @OnMessage public void onMessage(Session session, String message) { log.info("sessionId : {} , onMessage : {}", session.getId(), message); } /** * 发生错误 */ @OnError public void onError(Session session, Throwable error) { log.error("WebSocket发生错误:{},Session ID: {}", error, session.getId()); } /** * 服务器端推送消息 * * @param session session * @param message 消息 */ public static void sendMessage(Session session, String message) { try { if (session.isOpen()) { // 同步消息 session.getBasicRemote().sendText(message); // 异步消息 //session.getAsyncRemote().sendText(message); } } catch (IOException e) { e.printStackTrace(); log.error("WebSocket发送消息出错:{}", e.getMessage()); } } }
可参考:https://blog.lqdev.cn/2018/08/14/springboot/chapter-nineteen/