Reputation: 3093
I have a node.js script that when a client connects reads and dumps the contents of a Mongo DB. I've just upgraded from socket.io 0.9 and the lack of examples & poor docs have left me somewhat confused.
I used to be able to set options using io.set('transports', ['xhr-polling'])
but this has been removed, from what I can work out the new way to define options is like this
{
allowUpgrades: false,
transports: [ 'polling' ],
pingTimeout: 5000,
pingInterval: 2500
};
But... They appear to be being ignored.
Here is the full node.js script;
var io = require('socket.io')(8002, options);
cp = require('child_process');
var tail = cp.spawn('test-scripts/k-test.rb');
var options = {
allowUpgrades: false,
transports: [ 'polling' ],
pingTimeout: 5000,
pingInterval: 2500
};
//On connection do the code below//
io.on('connection', function (socket) {
console.log();
//Read the state list from db//
var connection_string = '127.0.0.1:27017/test';
var mongojs = require('mongojs');
var db = mongojs(connection_string, ['k1']);
var k1 = db.collection('k1');
db.k1.find({}, {'_id': 0, "data.time":0}).forEach(function(err, doc) {
if (err) throw err;
if (doc) { io.emit('k1', doc); }
});
When a client connects it still gets upgraded to a web-socket connection rather than staying as a polling session. The pingTimeout
& pingInterval
don't work - if I connect from a mobile client it takes at least 1 min from the time I close the browser to the time the server says the client has timed out.
Can anyone point me in the right direction please as to where I'm going wrong. I can provide the old (0.9) code if it's any help.
Update:
Fixed with answer from @mscdex below. A helpful note for anyone else - if you have debug enabled then when the options are being read at start-up you should get an output like this; socket.io:server creating engine.io instance with opts {"allowUpgrades":false,"transports":["polling"],"pingTimeout":10000,"pingInterval":5000,"path":"/socket.io"} +9ms
Upvotes: 1
Views: 520
Reputation: 106696
The problem is that you are trying to use options
before it is actually set. Variables themselves are hoisted in JavaScript, but their assignments like that are not. This means you are actually passing in undefined
(which probably causes defaults to be loaded) instead of your options
object.
The solution is to set options
before you reference it. For example:
var options = {
allowUpgrades: false,
transports: [ 'polling' ],
pingTimeout: 5000,
pingInterval: 2500
};
var io = require('socket.io')(8002, options);
// ...
Upvotes: 4