I have a page which opens a websocket connection (socket.io) to a node.js server.
For testing purposes I want to open the page with a headless browser, using CasperJs (I also tried pure PhantomJs with the same result).
Summary:
Open socket.io connection using Chrome always works.
Open socket.io connection using CasperJs always works (at least the corresponding callbacks on client and server are executed).
Message exchange (socket.emit) using Chrome always works.
Message exchange (socket.emit) using CasperJs sometimes works.
I get the same behaviour when I configure socket.io to use polling only instead of websocket. I know "sometimes" isn't very accurate, but I haven't found a "patter" yet when it happens.
Did you use a headless browser to open a page with socket.io/websockets successfully? Do you have any hints what might be the reason?
Some more details:
My client performs an
var socket = io.connect('http://localhost:3000');
After that on the server the connection method is called (it prints the transport type and socket id for debugging):
io.on('connection', function (socket) {
console.log('Client connect ('+ socket.client.conn.transport.constructor.name +'): ' + socket.id);
...
}
The output is as expected (socket.io uses XHR at first and then upgrades to websocket):
Client connect (XHR): d-moyZ_D6Z6eG7SNAAAA
Also on the client-side the connect callback is executed:
socket.on('connect', function () {
console.log("Client successfully connected to data server. Transport type: " + socket.io.engine.transport.constructor.name);
...
}
The output on the client console is as expected:
Client successfully connected to data server. Transport type: XHR
If I use a normal browser I can exchange messages without problems. If I use my casper script the message exchange sometimes works. In most cases just nothing happens when I call socket.emit. The casper script is pretty basic. I had the feeling that it might be a timing issue, so I created a wait for the javascript resource which performs the connection, no change:
casper = require('casper').create({
verbose: true,
logLevel: "debug"
});
casper.start('page.html', function() {
this.echo(this.getTitle());
});
casper.waitForResource("dataConnection.js", function() {
this.echo('socket.io has been loaded.');
this.wait(14000, function() {
this.echo("I've waited for some seconds.");
});
this.capture('casper.png');
});
casper.on('remote.message', function(message) {
console.log(message);
});
casper.run();
The disconnect callbacks on client/server are also executed as expected. You can see that the upgrade to websocket worked:
Client disconnect (WebSocket): d-moyZ_D6Z6eG7SNAAAA connectionCount: 0
Thank you!