Adding data to a socket.io socket object

柔情痞子 提交于 2020-01-21 11:11:58

问题


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

回答1:


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

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



来源:https://stackoverflow.com/questions/17351881/adding-data-to-a-socket-io-socket-object

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