Netty的AttributeMap

Netty的AttributeMap

AttributeMap接口

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

简单应用:

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

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
					Attribute<ChannelID> 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<ChannelID> 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<SocketChannel>() {  
	                          
	                        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<SocketChannel>() {  
	                 @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;
	}
	
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值