在不同的子域上使用Socket.IO服务器和客户端 [英] Using Socket.IO server and client on different subdomains

查看:93
本文介绍了在不同的子域上使用Socket.IO服务器和客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个子域名:


  • socket.mydomain.com - Socket.IO服务器

  • app.mydomain.com - 我想要连接到我的网络套接字的网络应用。

在目标网页中对于app.mydomain.com,我已在Socket.IO客户端脚本中链接,并成功创建了一个IO对象,如下所示:

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>

但是,不要尝试连接到 socket.mydomain.com ,客户端正在尝试连接到 app.mydomain.com 。因为 app.mydomain.com 没有套接字,它会失败并继续重试。

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.

有没有办法将我的应用程序 app.mydomain.com 连接到我的套接字 socket.mydomain.com ?或者这是不可能的?

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

更新

大多数现有答案都与现在使用过时的代码来解决这个问题,因为Socket.IO最近升级到了1.0(事实上是1.4)。但是,即使考虑到这些代码更改,它似乎就像Socket.IO不允许我正在尝试做的事情。

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.

当Socket.IO与服务器建立初始连接时,它会发送一个XHR,其中 withCredentials 设置为true。但是你不能将 withCredentials 设置为true 并且允许服务器上的CORS。所以看起来我的问题实际上是,有没有解决这个问题的方法?

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?'

推荐答案

为了实现我想要的,几个我需要使用最新的Socket.IO语法:

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


  • 必须在 socket.mydomain.com server( Access-Control-Allow-Origin 标头设置为 *

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

必须在服务器上指定可接受的传输( socket.mydomain.com ):

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']
});


  • 必须在客户端指定远程服务器和可接受的传输( app.mydomain.com ):

    const socket = io('socket.mydomain.com', {
      transports: ['websocket', 'xhr-polling']
    });
    


  • 这篇关于在不同的子域上使用Socket.IO服务器和客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆