문제

Is there a way to keep state on a Channel. I'm writing a chat server and I want to keep information about the user that a Channel belongs to. I was thinking maybe Channel would provide a method to store a user object, but I can't see one. Is there a way to do this without needing something like a Map?

도움이 되었습니까?

해결책

1)You can set the state information in the channelHandlerContext, like below, and use it later.

   channelHandlerContext.setAttachment(yourObj);

   Object yourObj2 = channelHandlerContext.getAttachment();

2)Create a channel local and store state information there (channel local is like a thread local to specific a channel)

import org.jboss.netty.channel.ChannelLocal;

import java.util.Map;

public class UserInfoHolder {
     public final static ChannelLocal<Map<String, String>> USER_INFO = new     ChannelLocal<Map<String, String>>();
}


 //if you have the channel reference, you can store and retrieve information like this
 Map<String,String> userMap = ....

 //store
 UserInfoHolder.USER_INFO.set(channel, userMap);

 //retrive
 Map<String,String> userMap2 = UserInfoHolder.USER_INFO.get(channel);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top