How do I get the socket.id of a connection on the client side?

Im using the following code in index.js

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

      

the above code allows me to print the socket.id file to the console.

But when i try to print socket.id on client side using following code

<script>
var socket = io();
var id = socket.io.engine.id;
document.write(id);
</script>

      

it gives "null" as output in the browser.

+5


source to share


4 answers


You must wait for the event connect

before you can access the field id

:

With this parameter you will get access to sessionID

socket.id

      

Edit with:



Client side:

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

      

Server:

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

      

+13


source


The following code gives socket.id on the client side.



<script>
  var socket = io();
  socket.on('connect', function(){
var id = socket.io.engine.id;
  alert(id);
})
</script>

      

+4


source


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...
 }

      

+2


source


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

 let socket = io(); 
 //on connect Event 
 socket.on('connect', () => {
     //get the id from socket
     console.log(socket.id);
 });

      

0


source







All Articles