【发布时间】:2018-02-27 15:09:58
【问题描述】:
我正在寻找使用 Node 集群模块和 socket.io 运行 Node.js 应用程序。我使用粘性会话进行了设置,它可以工作,但我的问题如下:
例如,如果我连接到工人 5。
例如,另一个人连接到工人 4。
当我发送消息时,只有同一个工作人员的其他人会收到消息,但我希望如果我在 1 个工作人员上发送消息,它也会发送给其他工作人员。
这是我的服务器代码。
var sticky = require('sticky-session'),
http = require('http'),
express = require('express'),
socketIO = require('socket.io'),
cluster = require('cluster'),
port = process.env.PORT || 3003;
var app = express(), io;
server = http.Server(app);
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io = socketIO(server);
let totalUsers = 0;
io.on('connection', function(socket) {
socket.on('chat message', function(msg) {
console.log("got request");
io.emit('chat message', msg+" send by worker "+cluster.worker.id);
});
});
if(!sticky.listen(server,port))
{
server.once('listening', function() {
console.log('Server started on port '+port);
});
if (cluster.isMaster) {
console.log('Master server started on port '+port);
}
}
else {
console.log('- Child server started on port '+port+' case worker id='+cluster.worker.id);
}
这是我的客户代码
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#messages { margin-bottom: 40px }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
window.scrollTo(0, document.body.scrollHeight);
});
});
</script>
</body>
</html>
【问题讨论】:
标签: javascript node.js socket.io