简体   繁体   中英

Persisting data in TCP server while client channel is connected

I'm building a TCP Server using Netty. Is there any way to persist the connected client's session data while its channel exists?

for example, when a client connect to the server, I need to create its class instance and reuse in different ways when he send messages. something like the code below:

// this is called when the client connect to the server
public void channelActive(final ChannelHandlerContext ctx) {
    ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener(
        new GenericFutureListener<Future<Channel>>() {
            public void operationComplete(Future<Channel> future) throws Exception {
               // I need to create the class instance when the
               // client connects to the server
               ClientData clientData = new ClientData(ctx.channel()); 
               channels.add(ctx.channel()); 
             }
        }
    );
}

// this is called when the server receives a message from the connected client
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
   if("update".equals(msg)){
       // then I need the retrieve the data created 
       // in the ChannelActive method.
      clientData().update(); 
   }
}

While browsing for solutions, I found a few examples where the developer used a cache service (like memcache or redis) to store and retrieve the data related to the connected client.

But I wish to solve this without depending on a external process. Is there any way to achieve this? Any advice on the subject would be appreciated.

Thank you

You should use AttributeMap.attr(AttributeKey key) , which is inherited by ChannelHandlerContext :

Storing stateful information

AttributeMap.attr(AttributeKey) allow you to store and access stateful information that is related with a handler and its context. Please refer to ChannelHandler to learn various recommended ways to manage stateful information. [1]

[1][ http://netty.io/4.0/api/io/netty/channel/ChannelHandlerContext.html]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM