将数据添加到 socket.io 套接字对象 [英] Adding data to a socket.io socket object

查看:27
本文介绍了将数据添加到 socket.io 套接字对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在连接时向我的套接字对象添加一些自定义信息,以便当我断开套接字连接时,我可以读取该自定义信息.

I am trying to add some custom information to my socket object on connect, so that when I disconnect the socket, I can read that custom information.

IE:

// (Client)
socket.on('connect', function(data){
  socket.customInfo = 'customdata';
});

// (server)
socket.on('disconnect', function () {
  console.log(socket.customInfo);
});

推荐答案

因为它是 JavaScript,所以您可以自由地向任何对象添加属性(就像您所做的那样).然而,socket.io 确实为您提供了一种内置方式来做到这一点(因此您不必担心命名冲突):

Since it is JavaScript you can freely add attributes to any object (just as you did). However socket.io does give you a built-in way to do that (so you won't have to worry about naming conflicts):

socket.set('nickname', name, function () {
  socket.emit('ready');
});

socket.get('nickname', function (err, name) {
  console.log('Chat message by ', name);
});

请注意,这仅在一侧(客户端或服务器).显然,您无法在没有通信的情况下在客户端和服务器之间共享数据(这就是您的示例所建议的).

Note that this is only on one side (either client or server). Obviously you can't share data between client and server without communication (that's what your example suggests).

浏览器中的 socket 和服务器中的 socket 如果您设置它们将不会共享相同的属性.基本上,您只在客户端设置了数据(在您的浏览器内存中,而不是在服务器上).

The socket in your browser and the socket in the server won't share the same properties if you set them. Basically you have set the data only at the client side (which is in your browsers memory NOT on the server).

这篇关于将数据添加到 socket.io 套接字对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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