Java 使用websocket

瑞星  金牌会员 | 2025-2-22 16:48:59 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 987|帖子 987|积分 2961

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
添加依赖

  1. <!-- WebSocket 支持 -->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-websocket</artifactId>
  5. </dependency>
复制代码
添加设置类

  1. @Configuration
  2. public class WebSocketConfig {
  3.     @Bean
  4.     public ServerEndpointExporter serverEndpointExporter(){
  5.         return new ServerEndpointExporter();
  6.     }
  7. }
复制代码
添加服务类

  1. @Component
  2. @ServerEndpoint("/ws/{clientId}")
  3. public class WebSocketServer {
  4.     private static Map<String, Session> sessionMap = new HashMap<>();
  5.     @OnOpen
  6.     public void onOpen(Session session, @PathParam("clientId") String clientId) {
  7.         System.err.println("客户端:" + clientId + "建立连结");
  8.         sessionMap.put(clientId, session);
  9.     }
  10.     @OnClose
  11.     public void onClose(@PathParam("clientId") String clientId) {
  12.         sessionMap.remove(clientId);
  13.     }
  14.     /**
  15.      * 收到客户端消息后调用的方法
  16.      *
  17.      * @param message  客户端发送过来的消息
  18.      * @param clientId
  19.      */
  20.     @OnMessage
  21.     public void onMessage(String message, @PathParam("clientId") String clientId) {
  22.         System.err.println("收到来自客户端" + clientId + "的消息:" + message);
  23.     }
  24.     public void sendMessage(String message) {
  25.         Collection<Session> sessions = sessionMap.values();
  26.         for (Session session : sessions) {
  27.             try {
  28.                 session.getBasicRemote().sendText(message);
  29.             } catch (Exception e) {
  30.                 e.printStackTrace();
  31.             }
  32.         }
  33.     }
  34. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

瑞星

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表