Eldar Nezametdinov
Eldar Nezametdinov

Reputation: 1925

Emit to a specific client with socketId via Socket.IO 1.0

I know it's very popular question, but i didn't find answer for my question. Very similar question: socket.IO: how can i get the socketid when i emit to a specific client in socket.io 1.0

I want emit to a specific client with socketId, But i get an error, see below.

socket.join( gameId );
io.sockets.connected( opponent ).join( gameId );
socket.emit( 'ready', gameId, 'X', x, y );
io.sockets.connected( opponent ).emit( 'ready', gameId, 'O', x, y );

Error:

          io.sockets.connected( opponent ).join( gameId );
                     ^
TypeError: Property 'connected' of object #<Namespace> is not a function

Please help me. Forgot to say that, impossible to use .join(gameId) with io.to(socket.id)

Upvotes: 0

Views: 1485

Answers (2)

DerM
DerM

Reputation: 1526

I'm not sure if I totally get your question, but you can emit to a specific socket id by emitting to the default room of the socket. Every socket is joining a default room with the id of the socket as name.

http://socket.io/docs/rooms-and-namespaces/#default-room

Upvotes: 0

vaibhavmande
vaibhavmande

Reputation: 1111

To join a room

socket.on('someEventName', function(Param){
    try {
        socket.join('A_Temporary_Room');    
    } catch(err) {
        console.log(err);
    }
});

To send a message to all members in this room

io.sockets.in('A_Temporary_Room').emit('ready', 'String');

EDIT

socket.on('setId', function(SocketId) {
    socket.set('socketId', SocketId, function(data){
        //callback
        /* Here you can maintain an array of all connected clients like
            clients[SocketId].push(socket); Where clients is an object.
         */
    });
});

Now to emit an event to a specific client use this

clients[SocketId].emit('PrivateMessage', 'This is a private message');

Upvotes: 1

Related Questions