Netty的AttributeMap

Netty的AttributeMap

AttributeMap接口

public interface AttributeMap {  
     Attribute attr(AttributeKey key);  
}
AttributeMap接口只有一个attr()方法,接收一个AttributeKey类型的key,返回一个Attribute类型的value。按照Javadoc,AttributeMap实现必须是线程安全的。所有的Channel和ChannelHandlerContext实现了AttributeMap接口

简单应用:

public class AttributeMapID {
	public static final AttributeKey Channel_ID = AttributeKey.valueOf("netty.channel");
}
public class ClienHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
					Attribute attribute =  ctx.attr(Channel_ID);
					ChannelID channelID = attribute.get();
					if (channelID==null) {
						ChannelID id = new ChannelID("link",new Date());
						channelID = attribute.setIfAbsent(id);
					} else {
						System.out.println("channelActive attributeMap 中是有值的");  
			            System.out.println(channelID.getName() + "=======" + channelID.getDate());  
					}
					  System.out.println("HelloWorldC0ientHandler Active");  
				        ctx.fireChannelActive();   
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		Attribute attribute =  ctx.attr(Channel_ID);
		ChannelID channelID = attribute.get();
		if (channelID==null) {
			ChannelID id = new ChannelID("link",new Date());
			channelID = attribute.setIfAbsent(id);
		} else {
			System.out.println("channelActive attributeMap 中是有值的");  
            System.out.println(channelID.getName() + "=======" + channelID.getDate());  
		}
		
		System.out.println("HelloWorldClientHandler read Message:" + msg);  
        
        ctx.fireChannelRead(msg);  
	}
		
}
public class Server {
	int port;
	public Server(int port) {
				this.port = port;
				start();
	}
	
	public void start() {
		  EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
	        EventLoopGroup workerGroup = new NioEventLoopGroup();  
	        try {  
	            ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))  
	                    .childHandler(new ChannelInitializer() {  
	                          
	                        protected void initChannel(SocketChannel ch) throws Exception {  
	                            ch.pipeline().addLast("decoder", new StringDecoder());  
	                            ch.pipeline().addLast("encoder", new StringEncoder());  
	                            ch.pipeline().addLast(new ServerHandler());  
	                        };  
	                          
	                    }).option(ChannelOption.SO_BACKLOG, 128)     
	                    .childOption(ChannelOption.SO_KEEPALIVE, true);  
	             // 绑定端口,开始接收进来的连接  
	             ChannelFuture future = sbs.bind(port).sync();    
	               
	             System.out.println("Server start listen at " + port );  
	             future.channel().closeFuture().sync();  
	        } catch (Exception e) {  
	            bossGroup.shutdownGracefully();  
	            workerGroup.shutdownGracefully();  
	        }  
	}
	
	
	
	public static void main(String[] args) {
			Server server = new Server(7788);
	}

}
public class ServerHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		 System.out.println("server channelRead..");  
	        System.out.println(ctx.channel().remoteAddress()+"->Server :"+ msg.toString());  
	        ctx.write("server write"+msg);  
	        ctx.flush();  
	}
		
}
public class Client {
		
	String host;
	int port;
	
	public Client(String host,int port) throws InterruptedException {
		// TODO Auto-generated constructor stub
		this.host = host;
		this.port =port;
		connect();
	}
	
	public void connect() throws InterruptedException {
		  EventLoopGroup group = new NioEventLoopGroup();  
	        try {  
	            Bootstrap b = new Bootstrap();  
	            b.group(group)  
	             .channel(NioSocketChannel.class)  
	             .option(ChannelOption.TCP_NODELAY, true)  
	             .handler(new ChannelInitializer() {  
	                 @Override  
	                 public void initChannel(SocketChannel ch) throws Exception {  
	                     ChannelPipeline p = ch.pipeline();  
	                     p.addLast("decoder", new StringDecoder());  
	                     p.addLast("encoder", new StringEncoder());  
	                     p.addLast(new ClienHandler());  
	                    
	                 }  
	             });  
	  
	            ChannelFuture future = b.connect(host,port).sync();  
	            future.channel().writeAndFlush("hello Netty,Test attributeMap");  
	            future.channel().closeFuture().sync();  
	        } finally {  
	            group.shutdownGracefully();  
	        }  
	}
	
	
	public static void main(String[] args) throws InterruptedException {
				Client client = new Client("127.0.0.1", 7788);
	}
}
public class ChannelID {
			
	String name;
	Date date;
	public ChannelID(String name,Date date) {
		// TODO Auto-generated constructor stub
		this.date = date;
		this.name = name;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	
	
	
}

你可能感兴趣的:(Java学习)