[JAVA] SpringBoot整合WebSocket实现后端向前端主动推送消息方式

1963 0
黑夜隐士 2022-11-8 17:48:31 | 显示全部楼层 |阅读模式
目录

    一、引入websocket依赖二、WebSocket配置三、WebSocket服务四、消息推送


一、引入websocket依赖
  1. <dependency>
  2.   <groupId>org.springframework.boot</groupId>
  3.   <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>
复制代码
二、WebSocket配置
  1. @Configuration
  2. public class WebSocketConfig {
  3.   @Bean
  4.   public ServerEndpointExporter serverEndpointExporter() {
  5.     return new ServerEndpointExporter();
  6.   }
  7. }
复制代码
三、WebSocket服务

(前端连接地址ws://ip:端口/websocket,请自行替换ip、端口和接口名称)
  1. @ServerEndpoint(value = "/websocket")
  2. @Component
  3. public class WebSocketServer {
  4.   private final static Logger log = LoggerFactory.getLogger(WeSocketServer.class);
  5.   //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
  6.   private static int onlineCount = 0;
  7.   //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
  8.   private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
  9.   //与某个客户端的连接会话,需要通过它来给客户端发送数据
  10.   private Session session;
  11.   /**
  12.   * 连接建立成功调用的方法
  13.   */
  14.   @OnOpen
  15.   public void onOpen(Session session) {
  16.     this.session = session;
  17.     //加入set中
  18.     webSocketSet.add(this);
  19.     //在线数加1
  20.     addOnlineCount();
  21.     log.info("有新连接加入!当前在线人数为" + getOnlineCount());
  22.     try {
  23.       sendMessage("连接成功");
  24.     } catch (IOException e) {
  25.       log.error("websocket IO异常");
  26.     }
  27.   }
  28.   /**
  29.   * 连接关闭调用的方法
  30.   */
  31.   @OnClose
  32.   public void onClose() {
  33.     //从set中删除
  34.     webSocketSet.remove(this);
  35.     //在线数减1
  36.     subOnlineCount();
  37.     log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
  38.   }
  39.   /**
  40.   * 收到客户端消息后调用的方法
  41.   *
  42.   * @param message 客户端发送过来的消息
  43.   */
  44.   @OnMessage
  45.   public void onMessage(String message, Session session) {
  46.     log.info("来自客户端的消息:" + message);
  47.     //群发消息
  48.     for (WebSocketServer item : webSocketSet) {
  49.       try {
  50.         item.sendMessage(message);
  51.       } catch (IOException e) {
  52.         e.printStackTrace();
  53.       }
  54.     }
  55.   }
  56.   /**
  57.   * @param session
  58.   * @param error
  59.   */
  60.   @OnError
  61.   public void onError(Session session, Throwable error) {
  62.     log.error("发生错误");
  63.     error.printStackTrace();
  64.   }
  65.   public void sendMessage(String message) throws IOException {
  66.     this.session.getBasicRemote().sendText(message);
  67.   }
  68.   /**
  69.   * 群发自定义消息
  70.   */
  71.   public static void sendInfo(String message) throws IOException {
  72.     log.info(message);
  73.     for (WebSocketServer item : webSocketSet) {
  74.       try {
  75.         item.sendMessage(message);
  76.       } catch (IOException e) {
  77.         continue;
  78.       }
  79.     }
  80.   }
  81.   public static synchronized int getOnlineCount() {
  82.     return onlineCount;
  83.   }
  84.   public static synchronized void addOnlineCount() {
  85.     WebSocketServer.onlineCount++;
  86.   }
  87.   public static synchronized void subOnlineCount() {
  88.     WebSocketServer.onlineCount--;
  89.   }
  90. }
复制代码
四、消息推送

后端调用WebServer的sendInfo接口(例如:WebSocketServer.sendInfo("Hello World");)实现主动向前端推送消息
以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行