所以我有一个适用于socket.io的应用程序,我正在努力让它在Heroku上工作但是遇到严重的问题让它运行。
在控制台日志和Chrome控制台中,每隔一秒左右就有一堆断开连接。在Chrome控制台中,我不断收到400个不良请求。
https://appname.herokuapp.com/socket.io/?api_key=xxx&EIO=3&transport=polling&t=1424782938420-1&sid=hcTvjdxYePd4kNS5AAAe Failed to load resource: the server responded with a status of 400 (Bad Request)
disconnect
WebSocket connection to 'wss://appname.herokuapp.com/socket.io/?api_key=xxx=3&transport=websocket&sid=hcTvjdxYePd4kNS5AAAe' failed: WebSocket is closed before the connection is established.
所以在我的server.js
var cluster = require('cluster');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var redis = require('redis');
var redisAdapter = require('socket.io-redis');
var port = process.env.PORT || 3800;
var workers = process.env.WORKERS || require('os').cpus().length;
var redisUrl = process.env.REDISTOGO_URL || 'redis://rediscloud:pw@url:14599';
var redisOptions = require('parse-redis-url')(redis).parse(redisUrl);
var pub = redis.createClient(redisOptions.port, redisOptions.host, {
detect_buffers: true,
auth_pass: redisOptions.password
});
var sub = redis.createClient(redisOptions.port, redisOptions.host, {
detect_buffers: true,
auth_pass: redisOptions.password
});
io.set('origins', '*:*');
io.adapter(redisAdapter({
pubClient: pub,
subClient: sub
}));
console.log('Redis adapter started with url: ' + redisUrl);
/* -------------------------------- */
//APP LOGIC HERE
/* -------------------------------- */
if (cluster.isMaster) {
console.log('start cluster with %s workers', workers - 1);
workers--;
for (var i = 0; i < workers; ++i) {
var worker = cluster.fork();
console.log('worker %s started.', worker.process.pid);
}
cluster.on('death', function(worker) {
console.log('worker %s died. restart...', worker.process.pid);
});
cluster.on('exit', function(worker) {
console.log('worker %s exited. restart...', worker.process.pid);
cluster.fork();
});
} else {
start();
}
function start() {
http.listen(port, function() {
console.log('listening on *:' + port);
});
}
在我的client.html
<script src="https://appname.herokuapp.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("https://appname.herokuapp.com", { query: "api_key=xxx" });
</script>
我读过粘性会话可能会导致问题,但大部分信息似乎已经过时,显然Heroku现在很好地支持websockets。
我不是试图在多个实例上运行它,这只是与heroku ps:scale web=1
甚至不确定websockets是否正常工作,它似乎正在使用轮询,然后也失败了。
所以我的问题:为什么我在本地工作正常时会收到所有这些断开连接和400个错误请求?我该如何解决?
答案 0 :(得分:2)
我有同样的问题。解决方案是改变主机。我不想从heroku搬家,因为它非常方便。但在我浪费了大量时间搜索修复后,我尝试将应用程序部署到OpenShift。 此外,我添加了修改后的服务器启动,提供了显式端口和主机(没有它就无法工作!)
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080,
ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
...
sockets.setupListeners(server);
server.listen(port, ip_address);
您可以在第4条enter link description here下找到更详细的信息。
我相信你会解决你的头痛问题。