简体   繁体   English

从服务器向客户端发送消息

[英]Send message to a client from server

I need to send message to clients from a netty server base on user names of clients. 我需要根据客户端的用户名从Netty服务器向客户端发送消息。 As a result I need to map channels with user name and find the channel each time I want to send message. 结果,我需要使用用户名映射频道,并在每次要发送消息时查找频道。

I have two approaches in my mind, the question is : Which approach is better, in term of performance in server side . 我脑中有两种方法,问题是:就服务器端的性能而言,哪种方法更好。 do you have any better idea ? 你有更好的主意吗?

  1. Map channels with user name in a hashmap. 在哈希图中使用用户名映射通道。

     //Send userName from client side in first request //Get userName in server side and put it in a map Map<String, Channel> userMap = new ConcurrentHashMap<String,Channel>(); //loop over userMap to find specific client 
  2. Set Attachment with user name. 用用户名设置附件。

     //Set the attachment in client side ctx.getChannel().setAttachment(username); //Put all channels to a default channel group //Get all channels, search in their attachments to find specific client 

From your code I suspect that the second option uses linear search to find a specific channel. 从您的代码中,我怀疑第二个选项使用线性搜索来找到特定的频道。 The first option would simple perform a get. 第一个选项将简单地执行获取。 (But the key must be string in this case) (但是在这种情况下,键必须是字符串)

Average linear search time: O(n/2) 平均线性搜索时间:O(n / 2)

Average hashmap access time: O(1)! 平均哈希图访问时间:O(1)! (see this posting for more information) (有关更多信息,请参见此发布

That means that the linear search gets worse if you have more channels. 这意味着如果您有更多的频道,线性搜索就会变得更糟。 The hashmap option is more stable and you can expect almost constant time access. hashmap选项更加稳定,您可以期待几乎恒定的时间访问。

What you could do is "fuse" both option, so you have the map to access the channels easily and the ChannelGroup for handling the difficult stuff. 您可以做的是“融合”两个选项,因此您可以轻松地访问通道的地图以及用于处理困难内容的ChannelGroup。 What you need to do is to remove the channel from the map when its closed. 您需要做的是在关闭通道后从地图中删除该通道。

如何创建一个“ UserInfo”对象,该对象包含用户名及其关联的频道?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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