Netty学习笔记15 Netty Attribute使用

历览千载书,时时见遗烈。这篇文章主要讲述Netty学习笔记15 Netty Attribute使用相关的知识,希望能为你提供帮助。
Attribute< ?> 用来在channel上记录数据。
操作
写示例

AttributeKey< byte[]> srcdataAttrKey = AttributeKey.valueOf("srcdata");
byte[] mydata=https://www.songbingjia.com/android/new byte[msg.readableBytes()];
Attribute< byte[]> srcdataAttr = ctx.channel().attr(CloudConstants.srcdataAttrKey);
srcdataAttr.set(mydata);

读示例
AttributeKey< String> nameAttrKey = AttributeKey.valueOf("nameattr");

Attribute< String> attr = ctx.channel().attr(nameAttrKey);
String name= attr.get();

通过attr查找channel
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelMatcher;
import io.netty.util.Attribute;

public class MatcherByNameimplements ChannelMatcher
private String name;

public MatcherByName(String name)
this.name = name;

/**
* 查找某个channel,找自己所在channel,不是找peer
*
* */
@Override
public boolean matches(Channel ch)

Attribute< String> nameAttr= ch.attr(ChannelConstants.ChannelAttribute);
String name = nameAttr.get();
if(name==null)return false;

if(this.name.equals(name))
return true;
else
return false;




/**
* 通过matcher找channel list
* @param matcher
* @return
*/
public static List< Channel> getChannelsFromMatcher(ChannelMatcher matcher)
Object[] channels =NettyService.allChannels.toArray();
List< Channel> list = new ArrayList< Channel> ();
Channel channel = null;
for(Object ch : channels)
if(matcher.matches((Channel)ch))
channel = (Channel)ch;
list.add(channel);


return list;


public static Channel getChannelByName(String name)
MatcherByName matcher=new MatcherByName(name);
List< Channel> list= getChannelsFromMatcher(matcher);
if(list!=null & & list.size()> 0)
return list.get(0);
else
return null;

【Netty学习笔记15 Netty Attribute使用】


    推荐阅读