WebSocketServerController.java 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. package com.studio.nx.im.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.zhengqing.modules.system.dto.output.MsgVO;
  4. import com.zhengqing.modules.system.entity.User;
  5. import com.zhengqing.modules.system.mapper.UserMapper;
  6. import com.zhengqing.utils.ApplicationContextUtil;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.stereotype.Component;
  9. import javax.websocket.*;
  10. import javax.websocket.server.PathParam;
  11. import javax.websocket.server.ServerEndpoint;
  12. import java.io.IOException;
  13. import java.util.ArrayList;
  14. import java.util.HashSet;
  15. import java.util.List;
  16. import java.util.Set;
  17. import java.util.concurrent.ConcurrentHashMap;
  18. /**
  19. * <p> websocket处理类Controller - 群聊 </p>
  20. * https://www.jianshu.com/p/3a5c58e921b7
  21. * https://www.cnblogs.com/liuyong1993/p/10718961.html
  22. */
  23. @Slf4j
  24. @Component
  25. @ServerEndpoint("/groupChat/{sid}/{userId}")
  26. public class WebSocketServerController {
  27. /**
  28. * 房间号 -> 组成员信息
  29. */
  30. private static ConcurrentHashMap<String, List<Session>> groupMemberInfoMap = new ConcurrentHashMap();
  31. /**
  32. * 房间号 -> 在线人数
  33. */
  34. private static ConcurrentHashMap<String, Set<Integer>> onlineUserMap = new ConcurrentHashMap();
  35. /**
  36. * 收到消息调用的方法,群成员发送消息
  37. *
  38. * @param sid:房间号
  39. * @param userId:用户id
  40. * @param message:发送消息
  41. */
  42. @OnMessage
  43. public void onMessage(@PathParam("sid") String sid, @PathParam("userId") Integer userId, String message) {
  44. List<Session> sessionList = groupMemberInfoMap.get(sid);
  45. Set<Integer> onlineUserList = onlineUserMap.get(sid);
  46. // 先一个群组内的成员发送消息
  47. sessionList.forEach(item -> {
  48. try {
  49. // json字符串转对象
  50. MsgVO msg = JSONObject.parseObject(message, MsgVO.class);
  51. msg.setCount(onlineUserList.size());
  52. // json对象转字符串
  53. String text = JSONObject.toJSONString(msg);
  54. item.getBasicRemote().sendText(text);
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. });
  59. }
  60. /**
  61. * 建立连接调用的方法,群成员加入
  62. *
  63. * @param session
  64. * @param sid
  65. */
  66. @OnOpen
  67. public void onOpen(Session session, @PathParam("sid") String sid, @PathParam("userId") Integer userId) {
  68. List<Session> sessionList = groupMemberInfoMap.computeIfAbsent(sid, k -> new ArrayList());
  69. Set<Integer> onlineUserList = onlineUserMap.computeIfAbsent(sid, k -> new HashSet());
  70. onlineUserList.add(userId);
  71. sessionList.add(session);
  72. // 发送上线通知
  73. sendInfo(sid, userId, onlineUserList.size(), "上线了~");
  74. log.info("Connection connected");
  75. log.info("sid: {}, sessionList size: {}", sid, sessionList.size());
  76. }
  77. public void sendInfo(String sid, Integer userId, Integer onlineSum, String info) {
  78. // 获取该连接用户信息
  79. User currentUser = ApplicationContextUtil.getApplicationContext().getBean(UserMapper.class).selectById(userId);
  80. // 发送通知
  81. MsgVO msg = new MsgVO();
  82. msg.setCount(onlineSum);
  83. msg.setUserId(userId);
  84. msg.setAvatar(currentUser.getAvatar());
  85. msg.setMsg(currentUser.getNickName() + info);
  86. // json对象转字符串
  87. String text = JSONObject.toJSONString(msg);
  88. onMessage(sid, userId, text);
  89. }
  90. /**
  91. * 关闭连接调用的方法,群成员退出
  92. *
  93. * @param session
  94. * @param sid
  95. */
  96. @OnClose
  97. public void onClose(Session session, @PathParam("sid") String sid, @PathParam("userId") Integer userId) {
  98. List<Session> sessionList = groupMemberInfoMap.get(sid);
  99. sessionList.remove(session);
  100. Set<Integer> onlineUserList = onlineUserMap.get(sid);
  101. onlineUserList.remove(userId);
  102. // 发送离线通知
  103. sendInfo(sid, userId, onlineUserList.size(), "下线了~");
  104. log.info("Connection closed");
  105. log.info("sid: {}, sessionList size: {}", sid, sessionList.size());
  106. }
  107. /**
  108. * 传输消息错误调用的方法
  109. *
  110. * @param error
  111. */
  112. @OnError
  113. public void OnError(Throwable error) {
  114. log.info("Connection error");
  115. }
  116. }