Javascript 如何在客户端获取连接的socket.id?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44270239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:24:59  来源:igfitidea点击:

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

javascriptnode.jssocket.io

提问by Black Heart

Im using the following code in index.js

我在 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.

上面的代码让我在控制台中打印 socket.id。

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

但是当我尝试使用以下代码在客户端打印 socket.id 时

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

it gives 'null' as output in the browser.

它在浏览器中给出“null”作为输出。

回答by Sayuri Mizuguchi

You should wait for the event connectbefore accessing the idfield:

您应该connect在访问该id字段之前等待事件:

With this parameter, you will access the sessionID

使用此参数,您将访问 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;
  ...
});

回答by Sandeep Joel

For Socket 2.0.4 users

对于 Socket 2.0.4 用户

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

回答by Black Heart

The following code gives socket.id on client side.

以下代码在客户端提供 socket.id。

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

回答by rohit

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

要获取最新 socket.io 2.0 的客户端套接字 ID,请使用以下代码

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