Update query string parameter at socket.io reconnect

1nsane picture 1nsane · Feb 23, 2014 · Viewed 8.6k times · Source

I pass a custom query string containing an ID to authorize a client on the server when he is connecting via socket.io.

var env = {id:12345};
var socket = io.connect('https://example.com', {query:'i='+env.id, port:443, reconnect:false, secure:true});  

When a client disconnects for whatever reason, he can reconnect by simply calling the following function.

socket.socket.connect();

However, at the time of a reconnect env.id usually contains a different value than during the initial connect and I want to have the current value in the query string at each reconnect.

The above reconnect method sends the initial value again, even if env.id was changed to an other value meanwhile.

I tried to set the current parameters when calling the reconnect function, but that does not seem to work.

socket.socket.connect('https://example.com', {query:'i='+env.id, port:443, reconnect:false, secure:true})  

Is there a simple way to update just the query string with the current env.id value and then reconnect?

Or do I need to destroy the entire socket object once disconnected and then build up a new connection using var socket = io.connect() with the current id?

Answer

1nsane picture 1nsane · Feb 25, 2014

I analyzed the socket object and found the solution, therefore I am answering my own question.

The query string is stored inside socket.socket.options.query. You can change it to the desired value directly before reconnecting.

socket.socket.options.query = 'i='+env.id;
socket.socket.connect();