简体   繁体   English

socket.io-如何加入房间

[英]socket.io - How to join a room

I am writing a chatting app. 我正在编写一个聊天应用程序。 Right now, when a new conversation between user A and user b is initiated by user A, user A sendS a socket message to server with user B's userId. 现在,当用户A启动用户A与用户b之间的新对话时,用户A将套接字消息与用户B的userId发送到服务器。

The Server checks whether there's a conversation existing between the two users, if not, creates one, and have user A join the new conversation(clientA.join(newConversationId)). 服务器检查两个用户之间是否存在对话,如果不存在,则创建一个对话,并让用户A加入新对话(clientA.join(newConversationId))。 But I don't know how to have user B join the room too if user B actually has a connected socket now. 但是我不知道如果用户B现在实际上已经连接了插座,那么如何让用户B也加入会议室。

What I think might work is keeping an object mapping userId to socket.id, so I can get user B's socket id by B's userId sent along with A's origin message. 我认为可能有效的方法是保留一个将userId映射到socket.id的对象,因此我可以通过将B的userId与A的原始消息一起发送来获取用户B的套接字ID。 And then I'll get B's socket by its socket ID, and have it join the conversation too. 然后,我将通过B的套接字ID来获取B的套接字,并使其也加入会话。

The problem is, I don't know how to get a socket by a socket ID. 问题是,我不知道如何通过套接字ID获取套接字。 I don't think there's an official document of this. 我认为没有正式的文件。 Or is there other better way to deal with something like this? 还是有其他更好的方法来处理这样的事情?

Yes, you have to keep track of your users id. 是的,您必须跟踪您的用户标识。 This code may help you a little with that. 这段代码可能会对您有所帮助。

 var io = require("socket.io").listen(conf.port); var customIds = []; io.on("connection", function (socket) { socket.on("login" function (data) { customIds[socket.id] = data.userId; }); /** * Executes when a client disconnect. * It deletes this client and updates and emits the client new client list */ socket.on("disconnect", function () { // leave the current room //socket.leave(socket.room); // emit event //socket.broadcast.to(socket.room).emit("clientDisconnected",customIds[socket.id])); // delete the custom id from the custom id array. customIds.splice(socket.id, 1); }); } 

You can also save your userid like this (Do not modify socket.id) 您也可以像这样保存用户标识(请勿修改socket.id)

socket.userId=XXXX

Get a list of clients and look for the user id you need 获取客户列表并查找所需的用户ID

io.sockets.clients();

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

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