netty ,向特定ip 的客户端发送 消息

package com.suning.server.netty;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suning.aad.common.protobuf.AadSocketMsgProto.AadSocketMsg;

/**
 * 
 * 
 * @author 14041292
 *
 */
public class SocketServerHandler extends ChannelHandlerAdapter {
	
	private final static Logger logger = LoggerFactory.getLogger(SocketServerHandler.class);
	
	private static Map<String, ChannelHandlerContext> cacheMap = new ConcurrentHashMap<String, ChannelHandlerContext>();
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		InetSocketAddress insocket =(InetSocketAddress) ctx.channel().remoteAddress();
		cacheMap.put(insocket.getAddress().getHostAddress(), ctx);
	}
    
    /**
     * 发送消息到指定ip的客户端
     * 
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
    	AadSocketMsg socketMsg = (AadSocketMsg)msg;
    	logger.info("cacheMap size:" + cacheMap.size());
    	logger.info(((AadSocketMsg)msg).toString());

    	for(String remoteAddress : cacheMap.keySet()){
    		if(!remoteAddress.contains(socketMsg.getIp())){
    			continue;
    		}
    		ChannelHandlerContext chctx = cacheMap.get(remoteAddress);
			chctx.writeAndFlush(msg);
    	}
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
    	ctx.flush();
    }
	
   @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("",cause);
        InetSocketAddress insocket =(InetSocketAddress) ctx.channel().remoteAddress();
        cacheMap.remove(insocket.getAddress().getHostAddress());
    }
}

 cacheMap 静态变量,存储连接到服务端的客户端channel 信息 

猜你喜欢

转载自yylcslg.iteye.com/blog/2291387