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 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 removeWebSocketChannel(Channel channel) { WEBSOCKET_GROUP.remove(channel); CHANNEL_MAP.remove(channel.id().asShortText()); } public static Channel findWebSocketChannel(String id){ ChannelId channelId = CHANNEL_MAP.get(id); 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)); } }