【问题标题】:Socket.IO with Node.js on HerokuHeroku 上带有 Node.js 的 Socket.IO
【发布时间】:2023-03-24 14:38:01
【问题描述】:

我使用 node.js 设置了 Socket.IO,它通过侦听/连接到端口 8000(或不是我的服务器正在运行的端口的另一个端口)在我的本地开发机器上工作。

当我尝试在 heroku 上做同样的事情时,我的客户端脚本导入失败。

我试过相对路径

<script src="/socket.io/socket.io.js"></script>

我也尝试绑定到 heroku 上的 8000 端口并使用完整路径名

<script type="text/javascript">
         var href = document.location.protocol + document.location.hostname + ':8000/socket.io/socket.io.js';
         console.log("href = " + href);
         document.write("<script src=" + href + "><\/script>");
     </script>

我确实读到 websockets 不能在 heroku 上工作,所以我在后端的 after_start.js 文件中有以下代码。除了将 socket.io 配置为使用传输/轮询之外,我还需要做其他事情吗?

var port = process.env.PORT || 8000; //I've tried hardcoding to 8000 and using process.env.PORT and then I used the relative path for the script import
io = require('socket.io').listen(port);
//Configue io to work with heroku
io.configure(function () { 
    io.set("transports", ["xhr-polling"]); 
    io.set("polling duration", 10); 
});

我在加载我的 heroku 应用程序时收到此错误:

GET http://<myAppName>.herokuapp.com/socket.io/socket.io.js 404 (Not Found) 

编辑:我实际上正在使用 geddy mvc 框架,并希望通过我在 heroku 上设置它的方式(基本上就像 socket.io)来工作,我发现这个答案让我看起来可以类似地使用它: GeddyJS & socket.io: catching and emitting events from server side

【问题讨论】:

  • 您需要让 socket.io 监听您的主 server 实例(与 Express 一起使用的实例)
  • 你是像express一样启动http服务器,还是只是socket.io?
  • 更新了原帖。我正在使用 Geddy。

标签: node.js heroku socket.io


【解决方案1】:

啊啊!我忘记在配置中打开 geddy 的实时设置了。

这是我所做的:

添加

, socketIo: true
, realtime: true

到配置文件

添加

geddy.io.configure(function () { 
    geddy.io.set("transports", ["xhr-polling"]); 
    geddy.io.set("polling duration", 10); 
});

到 after_start.js 文件

使用geddy.io.sockets.emit( 从后端发送事件。

&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;在前端导入io

var href = document.location.protocol + document.location.hostname;
console.log('href = ' + href);
var socket = io.connect(href);

从前端打开一个套接字。

【讨论】:

    猜你喜欢
    • 2012-07-25
    • 2013-03-16
    • 2016-07-08
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2014-06-28
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多