29

我有一个简单的 socket.io 聊天应用程序,我已将它上传到新的Heroku 'cedar'堆栈之一。

现在我几乎让一切正常,但我遇到了一个绊脚石。在我的本地主机上,我从客户端打开到套接字服务器的连接:

// lots of HTML omitted
socket = new io.Socket('localhost', {port: 8888});

但是在 Heroku 上,我显然必须用其他东西代替这些值。

我可以像这样从服务器上的进程对象获取端口:

port = process.env.PORT || 8888

并将其传递给视图。

但是我用什么代替'localhost'呢?

4

7 回答 7

21

根据heroku上的文章,正确的方法是:

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

这确保了 io.Socket 不会尝试使用 WebSockets。

于 2011-08-25T20:25:55.037 回答
14

通过执行以下操作,我能够让 Socket.IO v0.8 在 Heroku Cedar 上工作:

在 Express 应用程序中(在我的例子中是 CoffeeScript):

app = express.createServer();
socket = require("socket.io")

...

io = socket.listen(app);
io.configure () ->
  io.set("transports", ["xhr-polling"])
  io.set("polling duration", 10)

io.sockets.on('connection', (socket) ->
  socket.on('myaction', (data) ->
    ...
    socket.emit('result', {myData: data})

### The port setting is needed by Heroku or your app won't start
port = process.env.PORT || 3000;
app.listen(port);


在应用程序的前端 Javascript 中:

var socket = io.connect(window.location.hostname);
function sendSocketRequest() {
  socket.emit('myaction', $("#some_field").val());
}

socket.on('result', function(data) {
  console.log(data);
}

有用的网址:

于 2011-11-25T19:01:06.293 回答
10

从 2013 年 10 月起,这已经改变,heroku 添加了 websocket 支持:

https://devcenter.heroku.com/articles/node-websockets

利用:

heroku labs:enable websockets

要启用 websockets 并且不要忘记删除:

io.configure(function () { 
  io.set("transports", ["xhr-polling"]); 
  io.set("polling duration", 10); 
}); 
于 2013-10-09T08:35:53.257 回答
7

在阳光下尝试了每一种组合之后,我终于把它留空了。瞧,这完美无缺。你甚至不需要端口。

socket = new io.Socket();
于 2011-06-03T17:54:33.383 回答
2

我在heroku上也遇到了这个问题。我能够使用主机名“myapp.herokuapp.com”(或简单的window.location.hostname,在本地和生产环境中工作)并将端口设置为80。我使用的是SocketIO 0.6.0。

于 2011-07-07T19:57:43.623 回答
0

2011-06-25T21:41:31+00:00 heroku[router]: Error H13 (Connection closed without response) -> GET appxxxx.herokuapp.com/socket.io/1/websocket/4fd434d5caad5028b1af690599f4ca8e dyno=web.1 queue= wait= service= status=503 bytes=

这是否可能意味着应用程序前面的 heroku 路由器未配置为处理 Web 套接字流量?

[更新]截至 2011 年 6 月 22 日,答案是肯定的...... heroku 不支持 socket.io 看到这篇文章:http ://blog.heroku.com/archives/2011/6/22/the_new_heroku_2_node_js_new_http_routing_capabilities /

于 2011-06-25T21:42:51.450 回答
0

你不会只是输入你的实际主机名吗?

于 2011-06-03T13:42:30.397 回答