fuliqi
2025-02-14 c6976365d5bfb39a32db8b541b1fe3ceb30c7826
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.ycl.websocket;
 
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
 
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @author:xp
 * @date:2024/4/19 14:02
 */
public class NettyConnect {
 
    /**
     * netty提供的管理连接集合
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
 
    /**
     * 存放用户与Chanel的对应信息,用于给指定用户发送消息
     */
    private static ConcurrentHashMap<Long, Channel> userChannelMap = new ConcurrentHashMap<>(128);
 
    private NettyConnect() {}
 
    /**
     * 获取channel组
     * @return
     */
    public static ChannelGroup getChannelGroup() {
        return channelGroup;
    }
 
    /**
     * 移除channel时,同时移除用户对应关系
     *
     * @param channel
     */
    public static void removeChannel(Channel channel) {
        Long userId = null;
        for (Map.Entry<Long, Channel> channelEntry : userChannelMap.entrySet()) {
            if (Objects.equals(channel, channelEntry.getValue())) {
                userId = channelEntry.getKey();
                break;
            }
        }
        if (Objects.nonNull(userId)) {
            userChannelMap.remove(userId);
        }
        channelGroup.remove(channel);
    }
 
    /**
     * 获取用户channel map
     * @return
     */
    public static ConcurrentHashMap<Long, Channel> getUserChannelMap(){
        return userChannelMap;
    }
 
    /**
     * 移除用户关系时,同时移除连接
     *
     * @param userId
     */
    public static void removeUserChannel(Integer userId) {
        Channel channel = userChannelMap.get(userId);
        if (Objects.nonNull(userId)) {
            userChannelMap.remove(userId);
            channelGroup.remove(channel);
        }
    }
 
}