package com.monkeylessey.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 { /** * 定义一个channel组,管理所有的channel * GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例 */ private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); /** * 存放用户与Chanel的对应信息,用于给指定用户发送消息 */ private static ConcurrentHashMap userChannelMap = new ConcurrentHashMap<>(128); private NettyConnect() {} /** * 获取channel组 * @return */ public static ChannelGroup getChannelGroup() { return channelGroup; } /** * 移除channel时,同时移除用户对应关系 * * @param channel */ public static void removeChannel(Channel channel) { String userId = null; for (Map.Entry 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 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); } } }