gpt4 book ai didi

netty - 在 Netty channel 上保持状态

转载 作者:行者123 更新时间:2023-12-04 02:20:17 27 4
gpt4 key购买 nike

有没有办法在 channel 上保持状态。我正在编写一个聊天服务器,我想保留有关 channel 所属用户的信息。我在想也许 Channel 会提供一种方法来存储用户对象,但我看不到。有没有办法在不需要 Map 之类的东西的情况下做到这一点?

最佳答案

1)您可以在channelHandlerContext中设置状态信息,如下所示,稍后使用。

   channelHandlerContext.setAttachment(yourObj);

Object yourObj2 = channelHandlerContext.getAttachment();

2)在本地创建一个 channel 并将状态信息存储在那里( channel 本地就像一个特定于 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);

关于netty - 在 Netty channel 上保持状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377319/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com