参考文档
https://blog.csdn.net/qq_15807785/article/details/83547978
https://blog.csdn.net/u014534808/article/details/108906050

接口测试地址:
http://www.jsons.cn/websocket/

websocket特点

可以向客户端发送消息

特别注意:websocket接口类不能被自定义aop拦截,可能会出现问题

示例

添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>
  1. @Component
  2. public class WebSocketConfig {
  3. /**
  4. * ServerEndpointExporter作用
  5. * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
  6. */
  7. @Bean
  8. public ServerEndpointExporter serverEndpointExporter() {
  9. return new ServerEndpointExporter();
  10. }
  11. }
  12. @Slf4j
  13. @Component
  14. @ServerEndpoint("/ws/{name}")
  15. public class WebSocketController {
  16. /**
  17. * 与某个客户端的连接对话,需要通过它来给客户端发送消息
  18. */
  19. private Session session;
  20. /**
  21. * 标识当前连接客户端的用户名
  22. */
  23. private String name;
  24. private static ConcurrentHashMap<String, WebSocketController> websocketSet = new ConcurrentHashMap<>();
  25. @OnOpen
  26. public void OnOpen(Session session, @PathParam("name") String name) {
  27. this.session = session;
  28. this.name = name;
  29. //name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分
  30. websocketSet.put(name, this);
  31. log.info("[WebSocket]连接成功,当前连接人数为={}", websocketSet.size());
  32. }
  33. @OnClose
  34. public void OnClose() {
  35. websocketSet.remove(this.name);
  36. log.info("[WebSocket]退出成功,当前连接人数为={}", websocketSet.size());
  37. }
  38. @OnError
  39. public void onError(Throwable e) {
  40. // ......
  41. }
  42. @OnMessage
  43. public void OnMessage(String message) {
  44. log.info("[WebSocket]收到消息={}", message);
  45. groupSending("客户端的消息我已经收到了");
  46. System.out.println("receive " + message);
  47. }
  48. public void groupSending(String message) {
  49. for (String name : websocketSet.keySet()) {
  50. try {
  51. websocketSet.get(name).session.getBasicRemote().sendText(message);
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  57. }