Question

Y at-il un moyen de garder l'état sur un canal. J'écris un serveur de chat et je veux conserver des informations sur l'utilisateur qu'un canal appartient. Je pensais peut-être canal fournirait une méthode pour stocker un objet utilisateur, mais je ne vois pas un. Est-il possible de le faire sans avoir besoin quelque chose comme une carte?

Était-ce utile?

La 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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top