gpt4 book ai didi

node.js - 将 Node.js 集群与 socket.io 聊天应用程序结合使用

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:38 26 4
gpt4 key购买 nike

我正在尝试使用 socket.io 学习 Node.js 集群来创建聊天应用程序...问题是我似乎无法让事情正常工作。

我一直在尝试阅读所有教程,包括我从中获得的教程http://stackoverflow.com/questions/18310635/scaling-socket-io-to-multiple-node-js -processes-using-cluster/18650183#18650183

当我尝试打开两个浏览器时,消息不会发送到另一个浏览器。

这是我得到的代码

var express = require('express'),
cluster = require('cluster'),
net = require('net'),
socketio = require('socket.io'),
socket_redis = require('socket.io-redis');

var port = 3000,
num_processes = require('os').cpus().length;

if (cluster.isMaster) {
// This stores our workers. We need to keep them to be able to reference
// them based on source IP address. It's also useful for auto-restart,
// for example.
var workers = [];

// Helper function for spawning worker at index 'i'.
var spawn = function(i) {
workers[i] = cluster.fork();

// Optional: Restart worker on exit
workers[i].on('exit', function(code, signal) {
console.log('respawning worker', i);
spawn(i);
});
};

// Spawn workers.
for (var i = 0; i < num_processes; i++) {
spawn(i);
}

// Helper function for getting a worker index based on IP address.
// This is a hot path so it should be really fast. The way it works
// is by converting the IP address to a number by removing non numeric
// characters, then compressing it to the number of slots we have.
//
// Compared against "real" hashing (from the sticky-session code) and
// "real" IP number conversion, this function is on par in terms of
// worker index distribution only much faster.
var worker_index = function(ip, len) {
var s = '';
for (var i = 0, _len = ip.length; i < _len; i++) {
if (!isNaN(ip[i])) {
s += ip[i];
}
}

return Number(s) % len;
};

// Create the outside facing server listening on our port.
var server = net.createServer({ pauseOnConnect: true }, function(connection) {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
var worker = workers[worker_index(connection.remoteAddress, num_processes)];
worker.send('sticky-session:connection', connection);
}).listen(port);
} else {
// Note we don't use a port here because the master listens on it for us.
var app = new express();

// Here you might use middleware, attach routes, etc.
app.use('/assets', express.static(__dirname +'/public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});


// Don't expose our internal server to the outside.
var server = app.listen(),
io = socketio(server);

// Tell Socket.IO to use the redis adapter. By default, the redis
// server is assumed to be on localhost:6379. You don't have to
// specify them explicitly unless you want to change them.
io.adapter(socket_redis({ host: 'localhost', port: 6379 }));

// Here you might use Socket.IO middleware for authorization etc.

io.on('connection', function(socket) {
console.log('New client connection detected on process ' + process.pid);

socket.emit('welcome', {message: 'Welcome to BlueFrog Chat Room'});
socket.on('new.message', function(message) {
socket.emit('new.message', message);
})

});


// Listen to messages sent from the master. Ignore everything else.
process.on('message', function(message, connection) {
if (message !== 'sticky-session:connection') {
return;
}

// Emulate a connection event on the server by emitting the
// event with the connection the master sent us.
server.emit('connection', connection);

connection.resume();
});
}

最佳答案

如果我理解正确,您的问题是来自客户端的消息不会广播到其他客户端。您可以使用以下方法轻松解决此问题:

io.on('connection', function(socket) {
console.log('New client connection detected on process ' + process.pid);

socket.emit('welcome', {message: 'Welcome to BlueFrog Chat Room'});
socket.on('new.message', function(message) {
socket.emit('new.message', message); // this line sends the message back to the emitter
socket.broadcast.emit('my message', msg); // this broadcasts the message to all the clients
})

});

关于node.js - 将 Node.js 集群与 socket.io 聊天应用程序结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40885592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com