Spring Websocket使用指南

Spring Websocket使用指南

  1. 首先需要一个类去实现WebSocketConfigurer, 并且指定ws的地址
/**
* Represents the web socket configuration.
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
   private TextWebSocketHandler webSocketHandler;

   /**
    * Constructs the web socket config.
    *
    * @param webSocketHandler Web socket handler.
    */
   @Autowired
   WebSocketConfig(TextWebSocketHandler webSocketHandler) {
       this.webSocketHandler = webSocketHandler;
   }

   /**
    * Registers the web socket handlers.
    *
    * @param registry Web socket handler registry.
    */
   @Override
   public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
       registry.addHandler(webSocketHandler, "/ws").setAllowedOrigins("*");
   }
}
  1. 接下来需要定义一个WS请求的handler
/**
* Represents websocket handler.
*/
@Slf4j
@Service
public class WebSocketHandler extends TextWebSocketHandler {
   private WebSocketService webSocketService;

   /**
    * Constructs an web socket handler.
    *
    * @param webSocketService Application websocket service.
    */
   @Autowired
   public WebSocketHandler(WebSocketService webSocketService) {
       this.webSocketService = webSocketService;
   }

   /**
    * Event handler for after connection established event.
    *
    * @param session Session.
    */
   @Override
   public void afterConnectionEstablished(WebSocketSession session) {
       log.info("sessionId {} established", session.getId());
       webSocketService.put(session.getId(), session);
   }

   /**
    * Event handler for text message event.
    *
    * @param session Session.
    * @param message Message.
    */
   @Override
   protected void handleTextMessage(WebSocketSession session, TextMessage message) {
       log.info("get message from sessionId {} with message {}", session.getId(), message);
       webSocketService.onMessage(session.getId(), message);
   }

   /**
    * Event handler for transport error event.
    *
    * @param session   Session.
    * @param exception Exception.
    */
   @Override
   public void handleTransportError(WebSocketSession session, Throwable exception) {
       webSocketService.remove(session.getId());
   }

   /**
    * Event handler for after connection closed event.
    *
    * @param session     Session.
    * @param closeStatus Close status.
    */
   @Override
   public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
       webSocketService.remove(session.getId());
   }

   /**
    * Configures whether supports partial messages.
    */
   @Override
   public boolean supportsPartialMessages() {
       return false;
   }


}
  1. 具体实现handler中的对应策略
/**
* Websocket service.
*/
@Service
@Slf4j
public class WebSocketService {

   private final Map<String, WsPayloadSession> sessionMap = new HashMap<>();

   @Autowired
   public WebSocketService(RecgAtomService recgAtomService) {
       this.recgAtomService = recgAtomService;
   }

   public void put(String id, WebSocketSession webSocketSession) {
       WsPayloadSession wsPayloadSession = new WsPayloadSession();
       wsPayloadSession.setWebSocketSession(webSocketSession);
       sessionMap.put(id, wsPayloadSession);
       log.info("websocket connection {} open, now: {}", id, sessionMap.size());
   }

   public void remove(String sessionId) {
       if (sessionMap.containsKey(sessionId)) {
           try {
               sessionMap.get(sessionId).getConcurrentWebSocketSession().close();
               sessionMap.remove(sessionId);
               log.info("websocket connection {} closed, now: {}", sessionId, sessionMap.size());
           } catch (IOException e) {
               log.error("Failed to close session {}", sessionId);
           }
       }
   }

   void onMessage(String sessionId, TextMessage message) {
       if (sessionMap.containsKey(sessionId)) {
           try {
               WsRequestType wsRequestType = gson.fromJson(message.getPayload(), WsRequestType.class);
               if (null == wsRequestType) {
                   throw new JsonSyntaxException("Request type of null is not supported!");
               }
               WsPayloadSession wsPayloadSession = sessionMap.get(sessionId);
               // 这里可以在WsPayloadSession里加点自己的数据,如type, uuid之类的
               sendMessage(sessionId, gson.toJson(wsResponse));
           } catch (JsonSyntaxException e) {
               log.error("Unknown wsRequestType: {}", message.getPayload(), e);
           }
       } else {
           log.error("Websocket session {} is expired.", sessionId);
       }

   }

   public void sendMessage(String sessionId, String message) {
       TextMessage textMessage = new TextMessage(message);
       // your code
   }


   @Data
   private class WsPayloadSession {
       private WebSocketSession webSocketSession;
   }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值