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

后端 未结 4 1503
情歌与酒
情歌与酒 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:25

    To get client side socket id for Latest socket.io 2.0 use the code below

     let socket = io(); 
     //on connect Event 
     socket.on('connect', () => {
         //get the id from socket
         console.log(socket.id);
     });
    
    0 讨论(0)
  • 2021-01-31 06:26

    For Socket 2.0.4 users

    Client Side

     let socket = io.connect('http://localhost:<portNumber>'); 
     console.log(socket.id); // undefined
     socket.on('connect', () => {
        console.log(socket.id); // an alphanumeric id...
     });
    

    Server Side

     const io = require('socket.io')().listen(portNumber);
     io.on('connection', function(socket){
        console.log(socket.id); // same respective alphanumeric id...
     }
    
    0 讨论(0)
  • 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;
      ...
    });
    
    0 讨论(0)
  • 2021-01-31 06:34

    The following code gives socket.id on client side.

    <script>
      var socket = io();
      socket.on('connect', function(){
    var id = socket.io.engine.id;
      alert(id);
    })
    </script>
    
    0 讨论(0)
提交回复
热议问题