• SpringBoot集成WebSocket长连接实际应用详解


    https://www.tqwba.com/x_d/jishu/91989.html
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    2、封装WebSocketUtil工具类,用于提供对session链接、断开连接、推送消息的简单控制。
    
     public class WebsocketUtil {
      /**
       * 记录当前在线的Session
       */
      private static final Map<String, Session> ONLINE_SESSION = new ConcurrentHashMap<> ();
    
      /**
       * 添加session
       * @param userId
       * @param session
       */
      public static void addSession(String userId, Session session){
        // 此处只允许一个用户的session链接。一个用户的多个连接,我们视为无效。
        ONLINE_SESSION.putIfAbsent ( userId, session );
      }
    
      /**
       * 关闭session
       * @param userId
       */
      public static void removeSession(String userId){
        ONLINE_SESSION.remove ( userId );
      }
    
      /**
       * 给单个用户推送消息
       * @param session
       * @param message
       */
      public static void sendMessage(Session session, String message){
        if(session == null){
          return;
        }
    
        // 同步
        RemoteEndpoint.Async async = session.getAsyncRemote ();
        async.sendText ( message );
      }
    
      /**
       * 向所有在线人发送消息
       * @param message
       */
      public static void sendMessageForAll(String message) {
        //jdk8 新方法
        ONLINE_SESSION.forEach((sessionId, session) -> sendMessage(session, message));
      }
    }
    3、 WebSocketController
    如上,已经创建好了简单的session管理和消息管理,接下来要使用注解的方式,使用SpringBoot的websocket包提供的方法,实现OnOpen、OnClose、OnMessage三个方法,再实现一个OnError方法来应对异常。代码段如下:
    
    /**
     * websocket接口处理类
     */
    @Component
    @ServerEndpoint ( value = "/chat/{userid}" )
    public class WebsocketController {
    
      /**
       * 连接事件,加入注解
       * @param userId
       * @param session
       */
      @OnOpen
      public void onOpen( @PathParam ( value = "userid" ) String userId, Session session ) {
        String message ="[" + userId + "]加入聊天室!!";
    
        // 添加到session的映射关系中
        WebsocketUtil.addSession ( userId, session );
        // 广播通知,某用户上线了
        WebsocketUtil.sendMessageForAll ( message );
      }
    
      /**
       * 连接事件,加入注解
       * 用户断开链接
       * @param userId
       * @param session
       */
      @OnClose
      public void onClose(@PathParam ( value = "userId" ) String userId, Session session ) {
        String message ="[" + userId + "]退出了聊天室...";
    
        // 删除映射关系
        WebsocketUtil.removeSession ( userId );
        // 广播通知,用户下线了
        WebsocketUtil.sendMessageForAll ( message );
      }
    
      /**
       * 当接收到用户上传的消息
       * @param userId
       * @param session
       */
      @OnMessage
      public void onMessage(@PathParam ( value = "userId" ) String userId, Session session ,String message) {
        String msg ="[" + userId + "]:"+message;
    
        // 直接广播
        WebsocketUtil.sendMessageForAll ( msg );
      }
    
      /**
       * 处理用户活连接异常
       * @param session
       * @param throwable
       */
      @OnError
      public void onError(Session session, Throwable throwable) {
        try {
          session.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        throwable.printStackTrace();
      }
    }
    4、添加 ServerEndpointExporter 启动Bean
    
    public class DemoApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
      }
    
      /**
       * 会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
       * 要注意,如果使用独立的servlet容器,
       * 而不是直接使用springboot的内置容器,
       * 就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。
       */
      @Bean
      public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
      }
    }
  • 相关阅读:
    SpringMVC源码阅读-通过画图理解初始化(十一)
    通过Stratus 服务器在Flash Player中使用RTMFP 开发P2P应用
    Lucene 学习资料
    LIRe 源代码分析 3:基本接口(ImageSearcher)
    LIRe 源代码分析 2:基本接口(DocumentBuilder)
    LIRe 源代码分析 1:整体结构
    Media Player Classic
    ffdshow 源代码分析 5: 位图覆盖滤镜(总结)
    ITU-T Technical Paper: 测量QoS的基本网络模型
    ITU-T Technical Paper: QoS 测量 (目标,方法,协议)
  • 原文地址:https://www.cnblogs.com/tszr/p/16410294.html
Copyright © 2020-2023  润新知