9

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

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Apparently not. I'm using socket.io 1.3.4
2021 update: Use socket.data.
1

For anyone still looking for an answer, there are a couple of things you can do to share data from the client to the server without actually sending a message.

  1. Add a custom property to the auth property in the client socketIo options. This will be available to the server event handlers in socket.handshake.auth.xxxx.
  2. Add a custom header to the transportOptions.polling.extraHeaders property in the client socketIo options. This will ONLY be presented when the socket.io client is connected via polling and not when "upgraded" to websockets (as you can't have custom headers then).
  3. Add a custom query property to the client socketIo options. I don't recommend this since it potentially exposes the data to intermediate proxies.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.