实现代码
依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId></dependency>
启动类
@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
配置
@Configurationpublic class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Bean public ServerEndpointExporter serverEndpointExporter (){ return new ServerEndpointExporter(); } }
WebSocket
@ServerEndpoint("/websocket")@Componentpublic class MyWebSocket { private static AtomicLong onlineCount = new AtomicLong(); private static ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session) { webSocketMap.put(session.getId(), session); System.out.println("有新链接加入!当前在线人数为:\t" + onlineCount.incrementAndGet()); } @OnClose public void onClose(Session session) { webSocketMap.remove(session.getId()); System.out.println("有一链接关闭!当前在线人数为:\t" + onlineCount.decrementAndGet()); } @OnMessage public void onMessage(String message, Session session) throws IOException { System.out.println("收到消息:\t" + message); if (message.contains("#")) { String[] msgMap = message.split("#"); String targetId = msgMap[0]; String msg = String.format("[%s]:\t%s", session.getId(), msgMap[1]); session.getBasicRemote().sendText(message + "[self]"); // 单发消息 for (Session item : webSocketMap.values()) { if (item.getId().equals(targetId)) { sendMessage(item, msg); } } } else { String msg = String.format("[%s]:\t%s", session.getId(), message); session.getBasicRemote().sendText(msg + "[自己]"); // 群发消息 for (Session item : webSocketMap.values()) { if (!item.getId().equals(session.getId())) { sendMessage(item, msg); } } } } private void sendMessage(Session session, String message) throws IOException { session.getBasicRemote().sendText(message); } }
Github地址
https://github.com/dubby1994/web-socket
结果截图
第0个客户端
image
第1个客户端
image
第2个客户端
image
服务端
image
作者:我是杨正
链接:https://www.jianshu.com/p/220b610a94dd
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦