The very private rooms that you mention in your question are probably the right way to do this. However, you need to store links to your users and their respective sockets. Then, as soon as anonymous or any other - the user sends a private message to the registered user, simply attach them both to the same room.
var io = require('socket.io')(http); sockets = []; people = {}; io.on('connection', function (socket) { sockets.push(socket); //join the server io.on('join', function(name){ people[socket.id] = {name: name}; }) //disconnect from the server io.on('disconnect', function(){ delete people[socket.id]; sockets.splice(sockets.indexOf(socket), 1); }); //initiate private message io.on('initiate private message',function(receiverName, message){ var receiverSocketId = findUserById(receiverName); if(receiverSocketId){ var receiver = people[receiverSocketId]; var room = getARoom(people[socket.id], receiver); //join the anonymous user socket.join(room); //join the registered user sockets[receiverSocketId].join(room); //notify the client of this io.sockets.in(room).emit('private room created', room, message); // } }); io.on('send private message', function(room, message){ io.sockets.in(room).emit('private chat message', message); }); } //you could use eg underscore to achieve this ( function findUserByName(name){ for(socketId in people){ if(people[socketId].name === name){ return socketId; } } return false; } //generate private room name for two users function getARoom(user1, user2){ return 'privateRooom' + user1.name + "And" + user2.name; }
This, of course, is a very naive and incomplete solution! Users must have an id , and also make rooms, you need to check existing usernames, you will also really need to have links to rooms, etc., but you get the point, right?
An alternative would be to use whispers - you can send a message to only one socket = person using the following: io.sockets.socket(receiverSocketId).emit("whisper", message, extraInfo); . I would advise this, though, since this entails the need to carry out whispers going back and forth that can get pretty dirty.
source share