Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 lets me print the socket.id in console.

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

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

it gives 'null' as output in the browser.

like image 857
Black Heart Avatar asked May 30 '17 19:05

Black Heart


People also ask

How do I find my client id socket?

socket.id can be obtained after 'connect' event. Note, the socket.id on the server is not made available to the client, so if you want the id from the server, then you can send it to the client yourself in a message.

How do I connect Socket.IO to client side?

var socket = require('socket. io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket'); socket. on('connect', function() { console. log("Successfully connected!"); });

How do I know if Socket.IO client is connected?

You can check the socket. connected property: var socket = io. connect(); console.


2 Answers

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;   ... }); 
like image 124
Sayuri Mizuguchi Avatar answered Sep 28 '22 06:09

Sayuri Mizuguchi


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...  } 
like image 25
Sandeep Joel Avatar answered Sep 28 '22 07:09

Sandeep Joel