Dav*_*ite 28 sockets heroku node.js socket.io
我有一个简单的socket.io聊天应用程序,我已经上传到一个新的Heroku'cedar'堆栈.
现在我几乎把所有东西都搞定了,但我遇到了一个绊脚石.在我的localhost上,我从客户端打开与套接字服务器的连接:
// lots of HTML omitted
socket = new io.Socket('localhost', {port: 8888});
Run Code Online (Sandbox Code Playgroud)
但是在Heroku上,我显然必须用其他东西代替这些值.
我可以从服务器上的进程对象获取端口,如下所示:
port = process.env.PORT || 8888
Run Code Online (Sandbox Code Playgroud)
并将其传递给视图.
但是我该替代'localhost'什么呢?
Luk*_*ick 21
根据heroku 文章的正确方法是:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
socket = new io.Socket();
Run Code Online (Sandbox Code Playgroud)
这可以确保io.Socket不会尝试使用WebSockets.
Moo*_*lio 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);
Run Code Online (Sandbox Code Playgroud)
在您的应用程序的前端Javascript中:
var socket = io.connect(window.location.hostname);
function sendSocketRequest() {
socket.emit('myaction', $("#some_field").val());
}
socket.on('result', function(data) {
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
有用的网址:
截至2013年10月,这已经发生了变化,heroku已经添加了websocket支持:
https://devcenter.heroku.com/articles/node-websockets
使用:
heroku labs:enable websockets
Run Code Online (Sandbox Code Playgroud)
要启用websockets,别忘了删除:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
Run Code Online (Sandbox Code Playgroud)
在阳光下尝试每一个组合后,我终于把它留空了.瞧,这看起来很完美.你甚至不需要这个端口.
socket = new io.Socket();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15093 次 |
| 最近记录: |