how to get socket.id of a connection on client side?

后端 未结 4 1507
情歌与酒
情歌与酒 2021-01-31 06:05

Im using the following code in index.js

io.on(\'connection\', function(socket){
console.log(\'a user connected\');
console.log(socket.id);
});

4条回答
  •  执念已碎
    2021-01-31 06:34

    You should wait for the event connect before accessing the id field:

    With this parameter, you will access the sessionID

    socket.id
    

    Edit with:

    Client-side:

    var socketConnection = io.connect();
    socketConnection.on('connect', function() {
      const sessionID = socketConnection.socket.sessionid; //
      ...
    });
    

    Server-side:

    io.sockets.on('connect', function(socket) {
      const sessionID = socket.id;
      ...
    });
    

提交回复
热议问题