Tag - Spring

Spring Websocket Java    2019-02-20 22:46:59    10    0    0

Spring集成WebSocket即时推送

一、后端

1.代码部分

(1) 新建WebSocketHandler,实现WebSocketHandler接口或继承TextWebSocketHandler类

​ 若实现WebSocketHandler则需实现其中方法

  1. // 建立连接
  2. @Override
  3. public void afterConnectionEstablished(WebSocketSession session) throws Exception
  4. {}
  5. // 从客户端获取消息
  6. @Override
  7. public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
  8. throws Exception
  9. {}
  10. // 连接异常
  11. @Override
  12. public void handleTransportError(WebSocketSession session, Throwable exception)
  13. throws Exception
  14. {}
  15. // 连接关闭
  16. @Override
  17. public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
  18. throws Exception
  19. {}
  20. // 消息是否分片
  21. @Override
  22. public boolean supportsPartialMessages()
  23. {
  24. return false;
  25. }

​ 若继承TextWebSocketHandler则重写其中方法

  1. // 从客户端接收到文本消息
  2. @Override
  3. protected void handleTextMessage(WebSocketSession session, TextMessage message)
  4. throws Exception
  5. {}

(2) 新建WebSocketInterceptor,实现HandshakeInterceptor接口或继承HttpSessionHandshakeIn