Cross-domain connection in Socket.IO
**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.
Simply insert your remote domain name when creating the client side socket:
var socket = io.connect('http://example.com:8080');
Socket.io supports cross-domain connections, but keep in mind that your cookie will not be passed to the server. You'll have to either:
(1) come up with an alternate identification scheme (a custom token or a javascript cookie-- just keep in mind this should not be the actually session id, unless you want to put yourself at risk of session hijacking)
or (2) send a good old fashioned HTTP JSONP request to the server first to get the cookie. Then it will be transmitted w/ the socket connection handshake.
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.