当前位置:   article > 正文

spring-boot-starter-websocket入门demo

spring-boot-starter-websocket
使用spring-boot-starter-websocket构建前后台通信。

1.导入spring-boot-starter-websocket的jar包

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

2.session信息维护类

  1. @Slf4j
  2. public class WebSocketSessionManager {
  3. /**
  4. * 保存连接 session 的地方
  5. */
  6. public static ConcurrentHashMap<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();
  7. /**
  8. * 添加 session
  9. *
  10. * @param key
  11. */
  12. public static void add(String key, WebSocketSession session) {
  13. // 添加 session
  14. SESSION_POOL.put(key, session);
  15. }
  16. /**
  17. * 删除 session,会返回删除的 session
  18. *
  19. * @param key
  20. * @return
  21. */
  22. public static WebSocketSession remove(String key) {
  23. // 删除 session
  24. return SESSION_POOL.remove(key);
  25. }
  26. /**
  27. * 删除并同步关闭连接
  28. *
  29. * @param key
  30. */
  31. public static void removeAndClose(String key) {
  32. WebSocketSession session = remove(key);
  33. if (session != null) {
  34. try {
  35. // 关闭连接
  36. session.close();
  37. } catch (IOException e) {
  38. // todo: 关闭出现异常处理,添加错误处理逻辑
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. /**
  44. * 获得 session
  45. *
  46. * @param key
  47. * @return
  48. */
  49. public static WebSocketSession get(String key) {
  50. // 获得 session
  51. return SESSION_POOL.get(key);
  52. }
  53. }

3.websocket消息处理类

  1. @Component
  2. @Slf4j
  3. public class WebSocketHandler extends AbstractWebSocketHandler {
  4. @Override
  5. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  6. //socket连接成功后触发
  7. log.info("建立websocket连接");
  8. WebSocketSessionManager.add(session.getId(), session);
  9. }
  10. @Override
  11. protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
  12. // 客户端发送普通文件信息时触发
  13. log.info("发送文本消息");
  14. // 获得客户端传来的消息
  15. String payload = message.getPayload();
  16. log.info("服务端接收到消息 " + payload);
  17. }
  18. @Override
  19. protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
  20. //客户端发送二进信息是触发
  21. log.info("发送二进制消息");
  22. }
  23. @Override
  24. public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
  25. //异常时触发
  26. log.error("异常处理");
  27. WebSocketSessionManager.removeAndClose(session.getId());
  28. }
  29. @Override
  30. public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
  31. // socket连接关闭后触发
  32. log.info("关闭websocket连接");
  33. WebSocketSessionManager.removeAndClose(session.getId());
  34. }
  35. }

4.websocket配置类

  1. @Configuration
  2. @EnableWebSocket
  3. public class WebSocketConfig implements WebSocketConfigurer {
  4. @Autowired
  5. private WebSocketHandler webSocketHandler;
  6. @Override
  7. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  8. registry
  9. .addHandler(webSocketHandler, "/msg")//websocket连接地址 ws://localhost:8080/msg
  10. //允许跨域,方便本地调试,生产建议去掉
  11. .setAllowedOrigins("*");
  12. }
  13. }

 5.websocket操作相关服务类

  1. @Service
  2. @Slf4j
  3. public class WebSocketService {
  4. /**
  5. * 发送消息
  6. *
  7. * @param session
  8. * @param text
  9. * @return
  10. * @throws IOException
  11. */
  12. public void sendMsg(WebSocketSession session, String text) throws IOException {
  13. session.sendMessage(new TextMessage(text));
  14. }
  15. /**
  16. * 广播消息
  17. *
  18. * @param text
  19. * @return
  20. * @throws IOException
  21. */
  22. public void broadcastMsg(String text) throws IOException {
  23. for (WebSocketSession session : WebSocketSessionManager.SESSION_POOL.values()) {
  24. session.sendMessage(new TextMessage(text));
  25. }
  26. }
  27. }

6.项目启动类

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class WebSocketApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(WebSocketApplication.class, args);
  6. }
  7. }

7.定时测试向浏览器发送消息类

  1. @Slf4j
  2. @Component
  3. public class MessageJob {
  4. @Autowired
  5. WebSocketService webSocketService;
  6. /**
  7. * 每5s发送
  8. */
  9. @Scheduled(cron = "0/2 * * * * *")
  10. public void run(){
  11. try {
  12. webSocketService.broadcastMsg("服务端消息 " + LocalDateTime.now().toString());
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }

8.启动如报如下错误,增加定时任务配置类

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'defaultSockJsTaskScheduler' is expected to be of type 'org.springframework.scheduling.TaskScheduler' but was actually of type 'org.springframework.beans.factory.support.NullBean'
  1. @Configuration
  2. public class ScheduledConfig {
  3. @Bean
  4. public TaskScheduler taskScheduler() {
  5. ThreadPoolTaskScheduler scheduling = new ThreadPoolTaskScheduler();
  6. scheduling.setPoolSize(10);
  7. scheduling.initialize();
  8. return scheduling;
  9. }
  10. }

9.测试http://coolaf.com/tool/chattest在线工具进行调试

 

 

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

闽ICP备14008679号