fix
Helius
2022-06-27 7afcbeeb0e1c3003d1e3ef697b614209ea0adc4c
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
package com.xcong.farmer.cms.netty.common;
 
import com.alibaba.fastjson.JSONObject;
import com.xcong.farmer.cms.netty.bean.ResponseBean;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
 
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
 
/**
 * @author wzy
 * @email wangdoubleone@gmail.com
 * @date 2019-05-06
 */
public class ChannelManager {
 
    private static final ChannelGroup WEBSOCKET_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
 
    // 当前连接到服务器的通道(tcp和websocket)
    private static final ConcurrentMap<String, ChannelId> CHANNEL_MAP = new ConcurrentHashMap<>();
 
    public static void addWebSocketChannel(Channel channel) {
        WEBSOCKET_GROUP.add(channel);
        CHANNEL_MAP.put(channel.id().asShortText(), channel.id());
    }
 
    public static void addWsChannel(Channel channel, Long memberId) {
        WEBSOCKET_GROUP.add(channel);
        CHANNEL_MAP.put(memberId.toString(), channel.id());
    }
 
    public static void removeWebSocketChannel(Channel channel) {
        WEBSOCKET_GROUP.remove(channel);
        CHANNEL_MAP.remove(channel.id().asShortText());
    }
 
    public static void removeWsChannel(Channel channel, Long memberId) {
        WEBSOCKET_GROUP.remove(channel);
        CHANNEL_MAP.remove(memberId.toString());
    }
 
    public static Channel findWebSocketChannel(String id){
        ChannelId channelId = CHANNEL_MAP.get(id);
        return WEBSOCKET_GROUP.find(channelId);
    }
 
    public static Channel findWsChannel(Long id){
        ChannelId channelId = CHANNEL_MAP.get(id.toString());
        return WEBSOCKET_GROUP.find(channelId);
    }
 
    public static ChannelGroup getWebSocketGroup() {
        return WEBSOCKET_GROUP;
    }
 
    public static void send2All(Object object, String type) {
        if (WEBSOCKET_GROUP.size() == 0) {
            return;
        }
        ResponseBean responseBean = ResponseBean.ok(type, null);
        responseBean.putInfo("data", object);
        String msg = JSONObject.toJSONString(responseBean);
        WEBSOCKET_GROUP.writeAndFlush(NettyTools.webSocketBytes(msg));
    }
 
 
}