带有socket.io的节点群集

1u4esq0p  于 2021-06-10  发布在  Redis
关注(0)|答案(0)|浏览(258)

我有集群设置通过弹性豆茎和工作得很好。但是,当我尝试实现socket.io时,web套接字由于无法跨服务器通信而失败。所以,我改成 socket.io-redis 这是我用过的代码,但它一直给我 Cannot /Get 在浏览器中 localhost:3000 ```
var cluster = require('cluster');
var os = require('os');

if (cluster.isMaster) {
// we create a HTTP server, but we do not use listen
// that way, we have a socket.io server that doesn't accept connections
var server = require('http').createServer();
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');

io.adapter(redis({ host: 'localhost', port: 6379 }));

setInterval(function() {
// all workers will receive this in Redis, and emit
io.emit('data', 'payload');
}, 1000);

for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}

cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}else{
var express = require('express');
var app = express();

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');

io.adapter(redis({ host: 'localhost', port: 6379 }));
io.on('connection', function(socket) {
socket.emit('data', 'connected to worker: ' + cluster.worker.id);
});

app.listen(3000);
}

注意,我已经跑了 `redis-server` 我已经下载了模块。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题