Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Socket.IO server and client on different subdomains

I have two subdomains:

  • socket.mydomain.com - The Socket.IO server
  • app.mydomain.com - A web app that I'd like to connect to my web socket.

In the landing page for app.mydomain.com, I've linked in the Socket.IO client script, and successfully created an IO object, like so:

<script src=https://socket.mydomain.com/socket.io/socket.io.js></script>

<script type=text/javascript>
  const socket = io();
  socket.on('message', data => console.log(data));
</script>

However, rather than trying to connect to socket.mydomain.com, the client is trying to connect to app.mydomain.com. Because there's no socket at app.mydomain.com, it fails and keeps retrying.

Is there a way to connect my app at app.mydomain.com to my socket at socket.mydomain.com? Or is this impossible?

Update

Most all of the existing answers relating to this question now use outdated code, because Socket.IO has recently upgraded to 1.0 (1.4 in fact). However, even taking these code changes into account, it seems like Socket.IO doesn't allow what I'm trying to do.

When Socket.IO makes the initial connection to the server, it sends an XHR with the withCredentials settings set to true. But you can't have withCredentials set to true and allow CORS on the server. So it seems my question is actually, 'Is there a way around this problem?'

like image 233
dwhieb Avatar asked Apr 13 '16 06:04

dwhieb


1 Answers

To accomplish what I wanted, several things needed to be configured correctly, and I needed to use the latest Socket.IO syntax:

  • CORS must be enabled on the socket.mydomain.com server (Access-Control-Allow-Origin header set to *)

  • Acceptable transports had to be specified on the server (socket.mydomain.com):

    const app = express();
    const server = http.createServer(app);
    const io = require('socket.io')(server, {
      transports: ['websocket', 'xhr-polling']
    });
    
  • The remote server and acceptable transports had to be specified on the client (app.mydomain.com):

    const socket = io('socket.mydomain.com', {
      transports: ['websocket', 'xhr-polling']
    });
    
like image 199
dwhieb Avatar answered Sep 18 '22 01:09

dwhieb