如何在客户端获取连接的socket.id? [英] how to get socket.id of a connection on client side?

查看:30
本文介绍了如何在客户端获取连接的socket.id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 index.js 中使用以下代码

Im using the following code in index.js

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

上面的代码让我在控制台打印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

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

它在浏览器中给出null"作为输出.

it gives 'null' as output in the browser.

推荐答案

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

You should wait for the event connect before accessing the id field:

通过这个参数,您将访问 sessionID

With this parameter, you will access the sessionID

socket.id

客户端:

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

服务器端:

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

这篇关于如何在客户端获取连接的socket.id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆