当前位置:   article > 正文

springboot实现websocket_spring-boot-starter-websocket

spring-boot-starter-websocket

1、maven依赖

<!-- webSocket -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

2、新建 WebSocketStompConfig 类

  1. /**
  2. * 开启WebSocket支持
  3. */
  4. @Configuration
  5. public class WebSocketStompConfig {
  6. @Bean
  7. public ServerEndpointExporter serverEndpointExporter()
  8. {
  9. return new ServerEndpointExporter();
  10. }
  11. }

 3、新建 WebSocket

  1. /**
  2. * WebSocketServer
  3. */
  4. @Component
  5. @ServerEndpoint("/websocket/{username}")
  6. @Log4j2
  7. public class WebSocket {
  8. private Logger logger = LoggerFactory.getLogger(this.getClass());
  9. /**
  10. * 在线人数
  11. */
  12. public static int onlineNumber = 0;
  13. /**
  14. * 以用户的姓名为key,WebSocket为对象保存起来
  15. */
  16. private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
  17. /**
  18. * 会话
  19. */
  20. private Session session;
  21. /**
  22. * 用户名称
  23. */
  24. private String username;
  25. /**
  26. * 建立连接
  27. *
  28. * @param session
  29. */
  30. @OnOpen
  31. public void onOpen(@PathParam("username") String username, Session session) {
  32. onlineNumber++;
  33. logger.info("现在来连接的客户id:" + session.getId() + "用户名:" + username);
  34. this.username = username;
  35. this.session = session;
  36. logger.info("有新连接加入! 当前在线人数" + onlineNumber);
  37. try {
  38. //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
  39. //先给所有人发送通知,说我上线了
  40. Map<String, Object> map1 = new HashMap<>();
  41. map1.put("messageType", 1);
  42. map1.put("username", username);
  43. sendMessageAll(JSON.toJSONString(map1), username);
  44. //把自己的信息加入到map当中去
  45. clients.put(username, this);
  46. //给自己发一条消息:告诉自己现在都有谁在线
  47. Map<String, Object> map2 =new HashMap<>();
  48. map2.put("messageType", 3);
  49. //移除掉自己
  50. Set<String> set = clients.keySet();
  51. map2.put("onlineUsers", set);
  52. sendMessageTo(JSON.toJSONString(map2), username);
  53. } catch (IOException e) {
  54. logger.info(username + "上线的时候通知所有人发生了错误");
  55. }
  56. }
  57. @OnError
  58. public void onError(Session session, Throwable error) {
  59. logger.info("服务端发生了错误" + error.getMessage());
  60. //error.printStackTrace();
  61. }
  62. /**
  63. * 连接关闭
  64. */
  65. @OnClose
  66. public void onClose() {
  67. onlineNumber--;
  68. //webSockets.remove(this);
  69. clients.remove(username);
  70. try {
  71. //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
  72. Map<String, Object> map1 = new HashMap<>();
  73. map1.put("messageType", 2);
  74. map1.put("onlineUsers", clients.keySet());
  75. map1.put("username", username);
  76. sendMessageAll(JSON.toJSONString(map1), username);
  77. } catch (IOException e) {
  78. logger.info(username + "下线的时候通知所有人发生了错误");
  79. }
  80. logger.info("有连接关闭! 当前在线人数" + onlineNumber);
  81. }
  82. /**
  83. * 收到客户端的消息
  84. *
  85. * @param message 消息
  86. * @param session 会话
  87. */
  88. @OnMessage
  89. public void onMessage(String message, Session session) {
  90. try {
  91. logger.info("来自客户端消息:" + message + "客户端的id是:" + session.getId());
  92. JSONObject jsonObject = JSON.parseObject(message);
  93. String textMessage = jsonObject.getString("message");
  94. String fromusername = jsonObject.getString("username");
  95. String tousername = jsonObject.getString("to");
  96. //如果不是发给所有,那么就发给某一个人
  97. //messageType 1代表上线 2代表下线 3代表在线名单 4代表普通消息
  98. Map<String, Object> map1 = new HashMap<>();
  99. map1.put("messageType", 4);
  100. map1.put("textMessage", textMessage);
  101. map1.put("fromusername", fromusername);
  102. if (tousername.equals("All")) {
  103. map1.put("tousername", "所有人");
  104. sendMessageAll(JSON.toJSONString(map1), fromusername);
  105. } else {
  106. map1.put("tousername", tousername);
  107. sendMessageTo(JSON.toJSONString(map1), tousername);
  108. }
  109. } catch (Exception e) {
  110. logger.info("发生了错误了");
  111. }
  112. }
  113. public void sendMessageTo(String message, String ToUserName) throws IOException {
  114. for (WebSocket item : clients.values()) {
  115. if (item.username.equals(ToUserName)) {
  116. item.session.getAsyncRemote().sendText(message);
  117. break;
  118. }
  119. }
  120. }
  121. public void sendMessageAll(String message, String FromUserName) throws IOException {
  122. for (WebSocket item : clients.values()) {
  123. item.session.getAsyncRemote().sendText(message);
  124. }
  125. }
  126. public static synchronized int getOnlineCount() {
  127. return onlineNumber;
  128. }
  129. }

4、前端访问地址 ws://地址/用户名

5、发送信息格  (to = All:所有人)

{

    "message": "消息内容",

    "to": "All", 

    "username": "发送人名称"

}

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

闽ICP备14008679号