当前位置:   article > 正文

SpringBoot快速搭建WebSocket服务端和客户端_spring websocket client

spring websocket client

由于工作需要,研究了SpringBoot搭建WebSocket双向通信的过程,其他的教程看了许多,感觉讲得太复杂,很容易弄乱,这里我只展示快速搭建过程

SpringBoot-WebSocket

Server

引入SpringBoot集成WebSocket

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

配置WebSocketServerConfig

  1. @Configuration
  2. @EnableWebSocket
  3. public class WebSocketServerConfig implements WebSocketConfigurer {
  4. @Bean
  5. public WebSocketHandler webSocketHandler() {
  6. return new WebSocketServerHandler();
  7. }
  8. @Override
  9. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  10. registry
  11. .addHandler(webSocketHandler(), "/ws")//添加处理器并指定WebSocket的endpoint端点
  12. .setAllowedOrigins("*"); //允许跨域访问
  13. }
  14. }

配置WebSocketServerHandler

  1. @Slf4j
  2. public class WebSocketServerHandler extends TextWebSocketHandler {
  3. /**
  4. * 处理连接后的逻辑
  5. * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
  6. */
  7. @Override
  8. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  9. log.info("Server: WebSocket connection established");
  10. }
  11. /**
  12. * 处理客户端发送的消息
  13. * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
  14. * @param message:客户端发送的文本消息
  15. */
  16. @Override
  17. protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
  18. log.info("Server: Received message: " + message.getPayload());
  19. session.sendMessage(new TextMessage("Server: Hello, client!"));
  20. }
  21. }

Client

引入SpringBoot集成WebSocket

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

配置WebSocketClientConfig

  1. /**
  2. * WebSocket客户端配置
  3. * @author Lenovo
  4. * @date 2023/11/22
  5. */
  6. @Configuration
  7. @EnableScheduling
  8. public class WebSocketClientConfig {
  9. @Bean
  10. public WebSocketClientHandler myWebSocketClientHandler() {
  11. return new WebSocketClientHandler();
  12. }
  13. }

配置WebSocketClientHandler

  1. @Component
  2. @Slf4j
  3. @Data
  4. @ConfigurationProperties(prefix = "websocket")
  5. public class WebSocketClientHandler extends StandardWebSocketClient implements WebSocketHandler {
  6. private WebSocketSession session;
  7. private String url;
  8. /**
  9. * 连接WebSocket服务端
  10. */
  11. // @Scheduled(fixedDelay = 60000) // 每隔1分钟连接一次
  12. public void connect() throws Exception {
  13. WebSocketClient client = new StandardWebSocketClient();
  14. session = client.doHandshake(new WebSocketClientHandler(), url).get();
  15. log.info("Client: WebSocket connection established");
  16. }
  17. /**
  18. * 关闭WebSocket连接
  19. */
  20. @PreDestroy
  21. public void close() throws Exception {
  22. session.close();
  23. }
  24. /**
  25. * @param message:向服务端发送的消息
  26. */
  27. public void sendMessage(String message) throws Exception {
  28. session.sendMessage(new TextMessage(message));
  29. }
  30. // @Scheduled(fixedDelay = 5000)
  31. // public void sendMessage() throws Exception {
  32. // session.sendMessage(new TextMessage("message"));
  33. // }
  34. /**
  35. * 处理连接后的逻辑
  36. * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
  37. */
  38. @Override
  39. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  40. log.info("Client: WebSocket connection established");
  41. }
  42. /**
  43. * 处理客户端发送的消息
  44. * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
  45. * @param message:客户端发送的文本消息
  46. */
  47. @Override
  48. public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
  49. log.info("Client: Received message: " + message.getPayload());
  50. session.sendMessage(new TextMessage("Client: Hello, server!"));
  51. }
  52. /**
  53. * 处理发生的错误
  54. * @param session:WebSocketSession域对象,有获取通信信息,发送消息,打开关闭通道等等功能
  55. * @param exception:通信出现的异常
  56. */
  57. @Override
  58. public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
  59. log.info("Client: Error Occurred: " + exception.getMessage());
  60. }
  61. /**
  62. * 连接关闭
  63. */
  64. @Override
  65. public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
  66. log.info("Client: Connection Closed");
  67. }
  68. /**
  69. * 用于判断服务器或客户端是否支持分片消息partial message
  70. * WebSocket 协议规范要求所有的 WebSocket 实现都必须支持接收和处理完整的消息
  71. * @return boolean
  72. */
  73. @Override
  74. public boolean supportsPartialMessages() {
  75. return false;
  76. }
  77. }

这样就完成了整个搭建过程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号