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

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

    For Socket 2.0.4 users

    Client Side

     let socket = io.connect('http://localhost:'); 
     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...
     }
    

提交回复
热议问题