简体   繁体   English

使用nodejs向特定的websocket客户端发送消息

[英]Send message to specific websocket client using nodejs

I'm trying to implement a chat application (the client is an android app).我正在尝试实现一个聊天应用程序(客户端是一个 android 应用程序)。 Currently I'm using the ws package for the websocket, and I'm planning on storing the connection in an object using the user's id as the key for implementing sending to a specific client.目前,我正在将 ws package 用于 websocket,并且我计划将连接存储在 object 中,使用用户的 id 作为实现发送到特定客户端的密钥。

However I'm wondering if it has any negative impact because I'm storing that object globally in the memory.但是我想知道它是否有任何负面影响,因为我将 object 全局存储在 memory 中。 Would this be a good approach?这是一个好方法吗?

The alternative that I found is switching the lib to socket.io and using rooms.我发现的替代方法是将库切换到 socket.io 并使用房间。 This implementation seems a bit more straightforward and I think it would help me if I'll want to implement groups in the future.这个实现似乎更简单一些,我认为如果我将来想要实现组,它会对我有所帮助。 However, I'll have to refactor a bit of the code to use it.但是,我必须重构一些代码才能使用它。

I'm open to other suggestions我愿意接受其他建议

Rooms are the way go.房间的方式是go。 It allows you to use things like socket.io redis as well so you can use your socket server in a cluster mode.它还允许您使用 socket.io redis 之类的东西,因此您可以在集群模式下使用套接字服务器。

When creating a room you can choose set it up in such a way that its a group room OR private.创建房间时,您可以选择将其设置为团体房间或私人房间。 Rooms are just based off the name so a private room might be userID1 + userID2 or what ever to make it unique to just those two users ( you can also pass validation via JWT to ensure people have access )房间只是基于名称,所以私人房间可能是 userID1 + userID2 或任何使它对这两个用户唯一的东西(您也可以通过 JWT 验证以确保人们可以访问)

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

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