Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

**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.

Easy and security!

In the main file place it before io.on('connection'), add the lines:

io.set('origins', 'yoursite.com:*');

io.on('connection', function (socket) {

Yes it does. I have implemented cross domain socket.io to test whether it works.

<script src="http://your-nodejs-domain.com:3000/public/js/jquery.js"></script>
  <script src="http://your-nodejs-domain.com:3000/socket.io/socket.io.js"></script>
  <script>

      var socket = io.connect('http://your-nodejs-domain:3000');
      $(document).ready(function(){

          socket.on('test message', function(msg){
               console.log("Got the message: " + msg);
          });
      });

  </script>

That should work fine.

create your server by io like this:

const server = require('http').createServer();

const io = require('socket.io')(server, {
    origins:["127.0.0.1:8000"],
    path: '/',
    serveClient: false,
    // below are engine.IO options
    pingInterval: 20000,
    pingTimeout: 5000,
    cookie: false
});

io.on('connection', function(socket){
    console.log("here new user welcom")
});


server.listen(3000,function(){
    console.log('listening on *:3000')});

in the origins array specify valid origin

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top