SpringBoot集成WebSocket
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
|
添加WebSocketConfiguration配置
1 2 3 4 5 6 7
| @Configuration public class WebSocketConfiguration { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
|
主要逻辑类
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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| @Component @Slf4j @ServerEndpoint("/websocket/{userId}") public class WebSocket {
private static final CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();
private static final Map<String, Session> SESSION_POOL = new HashMap<>();
@OnOpen public void onOpen(Session session, @PathParam(value = "userId") String userId) { try { SESSIONS.add(session); SESSION_POOL.put(userId, session); log.info("总连接个数: " + SESSIONS.size()); } catch (Exception e) { e.printStackTrace(); } }
@OnClose public void onClose(Session session) { try { SESSIONS.remove(session); log.info("连接断开,总数为: " + SESSIONS.size()); } catch (Exception e) { e.printStackTrace(); } }
@OnMessage public void onMessage(String message, Session session) { log.info("收到客户端消息: " + message); sendOther(message, session); }
public void sendAllMessage(String message) { log.info("广播消息: " + message); for (Session session : SESSIONS) { try {
if (session.isOpen()) { session.getAsyncRemote().sendText(message); } } catch (Exception e) { e.printStackTrace(); } } }
public void sendOneMessage(String userId, String message) { Session session = SESSION_POOL.get(userId); if (session != null && session.isOpen()) { try { synchronized (session) { log.info("单点消息: " + message); session.getAsyncRemote().sendText(message); } } catch (Exception e) { e.printStackTrace(); } } }
public void sendMoreMessage(String[] userIds, String message) { for (String userId : userIds) { Session session = SESSION_POOL.get(userId); if (session != null && session.isOpen()) { try { log.info("单点消息(多个): " + message); session.getAsyncRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } } }
public void sendOther(String message, Session session) { SESSIONS.forEach((sessionItem -> { if (!session.getId().equals(sessionItem.getId())) { try { sessionItem.getAsyncRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } })); } }
|
测试
前端在线测试网页: http://coolaf.com/zh/tool/chattest
连接1

连接2

服务器打印日志
