Cross-domain connection in Socket.IO
Is it possible to use Socket.IO in a cross domain manner? If so, how? The possibility is mentioned around the web but no code examples are given anywhere.
Solution 1:
Quoting the socket.io FAQ:
Does Socket.IO support cross-domain connections?
Absolutely, on every browser!
As to how it does it: Native WebSockets are cross-domain by design, socket.io serves a flash policy file for cross-domain flash communication, XHR2 can use CORS, and finally you can always use JSONP.
Solution 2:
**Socket.IO version --> 1.3.7 **
Is it possible to use Socket.Io in a cross domain manner? Yes, absolutely.
If so, how?
Option 1: Force use of Websockets only
By default, websockets are cross domain. If you force Socket.io to only use that as means to connect client and server, you are good to go.
Server side
//HTTP Server
var server = require('http').createServer(app).listen(8888);
var io = require('socket.io').listen(server);
//Allow Cross Domain Requests
io.set('transports', [ 'websocket' ]);
Client side
var connectionOptions = {
"force new connection" : true,
"reconnectionAttempts": "Infinity", //avoid having user reconnect manually in order to prevent dead clients after a server restart
"timeout" : 10000, //before connect_error and connect_timeout are emitted.
"transports" : ["websocket"]
};
var socket = io("ur-node-server-domain", connectionOptions);
That's it. Problem? Won't work on browsers (for clients) who don't support websockets. With this you pretty much kill the magic that is Socket.io, since it gradually starts off with long polling to later upgrade to websockets (if client supports it.)
If you are 100% sure all your clients will access with HTML5 compliant browsers, then you are good to go.
Option 2: Allow CORS on server side, let Socket.io handle whether to use websockets or long polling.
For this case, you only need to adjust server side setup. The client connection is same as always.
Server side
//HTTP Server
var express=require('express');
//Express instance
var app = express();
//ENABLE CORS
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
That's it. Hope it helps anyone else.