Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top