Seeker
Seeker

Reputation: 2475

can i give my own id to a connected socket in nodejs

am trying to implement a multiuser communication app. I want to identify a user's socket with his id, so can i set socket's id to user' id like

socket.id=user.userId;

Upvotes: 2

Views: 5372

Answers (4)

Chanlito
Chanlito

Reputation: 2472

In socket.io when a user connects, socket.io will generate a unique socket.id which basically is a random unique unguessable id. What i'd do is after i connect i call socket.join('userId'). basically here i assign a room to this socket with my userId. Then whenever i want to send something to this user, i'd do like this io.to(userId).emit('my message', 'hey there?'). Hope this help.

Upvotes: 0

Paresh Thummar
Paresh Thummar

Reputation: 928

This may help you

io.sockets.on('connection', function (socket) {    
    console.log("==== socket  ===");
    console.log(socket.id);
    socket.broadcast.emit('updatedid', socket.id);
});

you can save socket id in client side. When you want 1-1 message (private chat) use updated socket id. Some thing like this :

io.sockets.socket(id).emit('private message', msg, mysocket.id) 

Upvotes: 3

Paresh Thummar
Paresh Thummar

Reputation: 928

Here

client side

var socket = io.connect();
     socket.on('connect', function () {
          console.log("client connection done.....");
          socket.emit('setUserId','random value');
});

On server side

io.sockets.on('connection', function (socket) {
       socket.on('setUserId',function(uId){
             socket.userId = uId;
        });
});

This may help...

Upvotes: 1

Teemu Ikonen
Teemu Ikonen

Reputation: 11929

You can do this, but use property that doesn't clash with Node.js or any other frameworks keys

socket.myappsuperuserid = user.userId;

Upvotes: 1

Related Questions