package com.xcong.excoin.netty.common;
|
|
import com.alibaba.fastjson.JSONObject;
|
import com.xcong.excoin.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<>();
|
|
// key - 用户ID value - 通道ID
|
private static final ConcurrentMap<String, ChannelId> MEMBER_CHANNEL = new ConcurrentHashMap<>();
|
|
// key - 通道 value - 用户
|
private static final ConcurrentMap<ChannelId, String> CHANNEL_MEMBER = 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) {
|
MEMBER_CHANNEL.put(memberId.toString(), channel.id());
|
CHANNEL_MEMBER.put(channel.id(), memberId.toString());
|
}
|
|
public static void removeWebSocketChannel(Channel channel) {
|
WEBSOCKET_GROUP.remove(channel);
|
CHANNEL_MAP.remove(channel.id().asShortText());
|
}
|
|
public static void removeWsChannel(Channel channel, Long memberId) {
|
MEMBER_CHANNEL.remove(memberId.toString());
|
CHANNEL_MEMBER.remove(channel.id());
|
}
|
|
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 = MEMBER_CHANNEL.get(id.toString());
|
if (channelId == null) {
|
return null;
|
}
|
|
return WEBSOCKET_GROUP.find(channelId);
|
}
|
|
public static String findWsMemberId(Channel channel) {
|
return CHANNEL_MEMBER.get(channel.id());
|
}
|
|
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));
|
}
|
|
|
}
|