Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding data to a socket.io socket object

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);
});
like image 694
Fostah Avatar asked Jun 27 '13 19:06

Fostah


1 Answers

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

like image 160
freakish Avatar answered Oct 10 '22 15:10

freakish