简体   繁体   中英

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.

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)). But I don't know how to have user B join the room too if user B actually has a connected socket now.

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. And then I'll get B's socket by its socket ID, and have it join the conversation too.

The problem is, I don't know how to get a socket by a socket 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.userId=XXXX

Get a list of clients and look for the user id you need

io.sockets.clients();

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