2

我正在尝试使用 socket.io 和 sticky-session 将消息传递给我的客户。

问题是连接到其中一个进程的客户端不会从其他进程获取消息,只会从他连接的进程获取消息。

如何使 Web 套接字在所有进程中工作?

服务器.js:

var cluster = require('cluster');
var app = require('./config/express')(db);

// Init the server to run according to server CPU's
if (cluster.isMaster) {
    for (var i = 0; i < 4; i++) {
        cluster.fork();
    }
} else {
    app.listen(config.port, function () {
        console.log('Process ' + process.pid + ' is listening to all incoming requests');
    });
}

Process.js:

var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);

var io = require('socket.io').listen(server);
var ns = io.of('/ns');

var sticky = require('sticky-session');

if (!sticky.listen(server, 8080)) {
    // Master code
    server.once('listening', function() {
        console.log('server started on 8080 port');
    });
}

客户端.js:

var io = require('socket.io-client');
var serverUrl = 'http://localhost:8080/ns';
var conn = io.connect(serverUrl);

conn.on('malware', function(infectedProcess){
    console.log('infectedProcess: ' + infectedProcess);
});
4

0 回答 0