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

纵然是瞬间 提交于 2019-12-31 08:39:10

问题


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.


回答1:


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



回答2:


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



回答3:


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>



回答4:


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);
 });


来源:https://stackoverflow.com/questions/44270239/how-to-get-socket-id-of-a-connection-on-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!