我正在尝试使用Socket.IO创建一个带有Node.JS和Websocket的简单聊天App。我通过这个German tutorial启发了自己,对于单个后端实例,它运作良好。
我希望在后端有2个服务器实例,它们应该在彼此之间同步聊天消息,并将聊天记录存储在redis中。当新的聊天室加入时,客户端应显示当前频道的最后10条消息。
我尝试应用此stackoverflow page的解决方案,但我遇到了一些问题。首先我得到
控制台中出现WebSocket连接到'ws:// localhost:8080 / socket.io /?EIO = 3& transport = websocket& sid = LEqGvY0CVk9YaSzBAAAA'失败:连接在收到握手响应之前关闭
错误。其次,两个客户端都在1秒的时间间隔内收到“有效载荷”消息。我可能不明白redis-sync机制是如何工作的,我还不知道如何显示聊天记录。
到目前为止,这是我的代码:
var conf = require('./config.json');
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: conf.redisUri, port: conf.redisPort }));
setInterval(function() {
// all workers will receive this in Redis, and emit
io.emit('chat', {time: new Date(), text:'payload'});
}, conf.syncIntervall);
// set number of workers
for (var i = 0; i < conf.numberOfWorkers; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}
if (cluster.isWorker) {
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');
// Webserver
//app.listen(conf.defaultPort);
server.listen(conf.defaultPort);
// deliver static files
app.use(express.static(__dirname + '/public'));
// route for the / path
app.get('/', function (req, res) {
// send the index.html in the reponse
res.sendfile(__dirname + '/public/index.html');
});
// Websocket
io.adapter(redis({ host: conf.redisUri, port: conf.redisPort }));
// Callback when a client connects
io.sockets.on('connection', function (socket) {
// store the room name in the socket session for this client
socket.room = 'defaultChannel';
// send client to room 1
socket.join('defaultChannel');
// echo to client they've connected
socket.emit('chat', { time: new Date(), text: 'You have connected to room defaultChannel on the server!' });
socket.emit('chat', { time: new Date(), text: 'Connected to chat worker-node: ' + cluster.worker.id});
// if a message is received
socket.on('chat', function (data) {
// the it will be send to all other clients
console.log('the current channel', socket.room);
socket.broadcast.in(socket.room).emit('chat', { time: new Date(), name: data.name || 'anonymous', text: data.text });
});
// if a client joins a channel
socket.on('join', function (room) {
// store the room name in the socket session for this client
socket.room = room;
// send client to room 1
socket.join(room);
console.log('Client joined room ' + room);
});
});
// Log port number in the console
console.log('Server running under http://127.0.0.1:' + conf.defaultPort + '/');
}