package com.casic.missiles.client; import io.netty.channel.Channel; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import org.springframework.util.CollectionUtils; import java.util.concurrent.ConcurrentHashMap; public class ChannelUtil { private static final ConcurrentHashMap<String, Channel> CHANNEL_MAP = new ConcurrentHashMap<>(128); public static ConcurrentHashMap<String, Channel> getChannelMap() { return CHANNEL_MAP; } /** * 获取指定name的channel */ public static Channel getChannelByName(String devCode){ if(CollectionUtils.isEmpty(CHANNEL_MAP)){ return null; } return CHANNEL_MAP.get(devCode); } /** * 将通道中的消息推送到每一个客户端 */ public static boolean pushNewsToAllClient(String obj){ if(CollectionUtils.isEmpty(CHANNEL_MAP)){ return false; } for(String devCode: CHANNEL_MAP.keySet()) { Channel channel = CHANNEL_MAP.get(devCode); channel.writeAndFlush(new TextWebSocketFrame(obj)); } return true; } /** * 将channel和对应的name添加到ConcurrentHashMap */ public static void addChannel(String devCode,Channel channel){ CHANNEL_MAP.put(devCode,channel); } /** * 移除掉name对应的channel */ public static boolean removeChannelByName(String devCode){ if(CHANNEL_MAP.containsKey(devCode)){ CHANNEL_MAP.remove(devCode); return true; } return false; } }