[英]Can I set up socket.io chat on heroku?
我有一個簡單的 socket.io 聊天應用程序,我已將其上傳到新的Heroku 'cedar'堆棧之一。
現在我幾乎讓一切正常,但我遇到了一個絆腳石。 在我的本地主機上,我從客戶端打開到套接字服務器的連接:
// lots of HTML omitted
socket = new io.Socket('localhost', {port: 8888});
但是在 Heroku 上,我顯然必須用其他東西代替這些值。
我可以從服務器上的進程 object 獲取端口,如下所示:
port = process.env.PORT || 8888
並將其傳遞給視圖。
但是我用什么來代替'localhost'
呢?
根據 heroku 上的文章,正確的方法是:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
socket = new io.Socket();
這確保了 io.Socket 不會嘗試使用 WebSocket。
通過執行以下操作,我能夠讓 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);
}
有用的網址:
從 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);
});
在陽光下嘗試了每一種組合之后,我終於把它留空了。 瞧,這完美無缺。 你甚至不需要端口。
socket = new io.Socket();
我在 heroku 上也遇到了這個問題。 我能夠使用主機名“myapp.herokuapp.com”(或簡單的 window.location.hostname,在本地和生產中工作)並將端口設置為 80 使其工作。我使用的是 SocketIO 0.6.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 套接字流量?
[update] It would appear as of 6/22/2011 the answer is yes... heroku does not support socket.io see this post: http://blog.heroku.com/archives/2011/6/22/the_new_heroku_2_node_js_new_http_routing_capabilities/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.