SocketUtil.java 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package com.sckj.common.socketio;
  2. import com.corundumstudio.socketio.SocketIOClient;
  3. import com.corundumstudio.socketio.annotation.OnEvent;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.util.StringUtils;
  7. import java.util.Map;
  8. import java.util.Objects;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. import java.util.concurrent.ConcurrentMap;
  11. /**
  12. * @Author sckj
  13. * @Date 2024-10-15 下午 04:41
  14. * @Description TODO
  15. */
  16. @Component
  17. @Slf4j
  18. public class SocketUtil {
  19. //暂且把用户&客户端信息存在缓存
  20. public static final ConcurrentMap<String, SocketIOClient> connectMap = new ConcurrentHashMap<>();
  21. public static final Map<SocketIOClient, String> clientUserIds = new ConcurrentHashMap<>();
  22. /**
  23. * 单发消息(以 userId 为标识符,给用户发送消息)
  24. *
  25. * @Param [userId, message]
  26. * @return
  27. **/
  28. public static void sendToOne(String userId, Object message) {
  29. //拿出某个客户端信息
  30. SocketIOClient socketClient = getSocketClient(userId);
  31. if (Objects.nonNull(socketClient) ){
  32. //单独给他发消息
  33. socketClient.sendEvent(SocketEventContants.CHANNEL_USER,message);
  34. }else{
  35. log.info(userId + "已下线,暂不发送消息。");
  36. }
  37. }
  38. /**
  39. * 群发消息
  40. *
  41. * @Param
  42. * @return
  43. **/
  44. public static void sendToAll(Object message) {
  45. if (connectMap.isEmpty()){
  46. return;
  47. }
  48. //给在这个频道的每个客户端发消息
  49. for (Map.Entry<String, SocketIOClient> entry : connectMap.entrySet()) {
  50. entry.getValue().sendEvent(SocketEventContants.CHANNEL_SYSTEM, message);
  51. }
  52. }
  53. /**
  54. * 根据 userId 识别出 socket 客户端
  55. * @param userId
  56. * @return
  57. */
  58. public static SocketIOClient getSocketClient(String userId){
  59. SocketIOClient client = null;
  60. if (StringUtils.hasLength(userId) && !connectMap.isEmpty()){
  61. for (String key : connectMap.keySet()) {
  62. if (userId.equals(key)){
  63. client = connectMap.get(key);
  64. }
  65. }
  66. }
  67. return client;
  68. }
  69. /**
  70. * 1)使用事件注解,服务端监听获取客户端消息;
  71. * 2)拿到客户端发过来的消息之后,可以再根据业务逻辑发送给想要得到这个消息的人;
  72. * 3)channel_system 之所以会向全体客户端发消息,是因为我跟前端约定好了,你们也可以自定定义;
  73. *
  74. * @Param message
  75. * @return
  76. **/
  77. @OnEvent(value = SocketEventContants.CHANNEL_SYSTEM)
  78. public void channelSystemListener(String message) {
  79. if (!StringUtils.hasLength(message)){
  80. return;
  81. }
  82. sendToAll(message);
  83. }
  84. }