I am trying to connect 2 sperate Node.js servers using Socket.io and Socket.io-client using cloudfoundry. When I test the code with both instances running locally the socket.io-client Node.js code below works as expected. When the socket.io server is cloudfoundry a simple javascript client in a browser is able to connect and works fine. However when I try to connect using the socket.io-client Node.js to the instance running on cloudfoundry it fails in a few different ways. It either does nothing, tries to connect twice and then fails, or does connect only to disconnect immediately.
The only thing I can think of is the nginx on cloudfoundry is causing something to break. It doesn't make sense to me that a javascript client in a browser can connect and send and receive data, while basically identical Node.js code run from the same machine as the web browser cannot connect. Any ideas or should I just move away from cloudfoundry?
var socketioclient = require('socket.io-client').connect('http://someapiaddress.cloudfoundry.com');
socketclient = socketioclient.socket;
socketclient.on('connect_failed', function(){
console.log('Connection Failed');
});
socketclient.on('connecting', function(){
console.log('connecting')
});
socketclient.on('connect', function(socket) {
console.log('Connected!');
socketclient.on('message', function(data){
console.log(data)
});
socketclient.on('disconnect', function(){
console.log('disconnect')
});
});
Yes, the nginx creates problems if you are running more than one server instance, intercepting the requests every time and sending socket.io requests to different server instances. This is why you get a number of different errors:
You have to use something called sticky sessions to deal this. See this link which explains the problem and gives the solution.