error socket.io redis multithread:套接字连接在收到握手响应之前关闭

时间:2016-07-13 16:22:59

标签: node.js multithreading socket.io

我的聊天示例socket.io multithread中有错误。 在随机cpu我有这个错误:

  

WebSocket连接到   ' WS://xx.xx.xx.xx:8000 / socket.io / EIO = 3及运输=网页套接字&安培; SID = G_Pd2cZPv5dXTw9GAAAN'   失败:在收到握手响应之前关闭连接

所以当我在其他cpu聊天时我工作正常

这是我的服务器代码:



var cluster = require('cluster');
var redis = require('redis');
var redisAdapter = require('socket.io-redis');
var port = process.env.PORT || 8000;
var workers = process.env.WORKERS || require('os').cpus().length;//nombre de coeurs dispo


//le worker s'abonne au redis locale
	var redisUrl = process.env.REDISTOGO_URL || 'redis://127.0.0.1:6379';
	var redisOptions = require('parse-redis-url')(redis).parse(redisUrl);
	var pub = redis.createClient(redisOptions.port, redisOptions.host, {
	  //detect_buffers: true,
	  return_buffers: true,
	  auth_pass: redisOptions.password
	});
	var sub = redis.createClient(redisOptions.port, redisOptions.host, {
	  //detect_buffers: true,
	  return_buffers: true,
	  auth_pass: redisOptions.password
	});


//-----------------------------------------
// If this worker is the Master process
// Setup everything we need to scale
//-----------------------------------------
if (cluster.isMaster) {
	console.log('start cluster Master with %s workers', workers - 1);
	workers--;
	for (var i = 0; i < workers; ++i) {
		var worker = cluster.fork();
		console.log('worker '+(i+1)+' started : pid:%s.', worker.process.pid);
	}

	cluster.on('death', function(worker) {
		console.log('worker est mort. restart...', worker.pid);
	});

	cluster.on('fork', function(worker) {
        console.log('worker %s créer', worker.id);
    });
    cluster.on('online', function(worker) {
         console.log('worker %s en ligne', worker.id);
    });
    cluster.on('listening', function(worker, addr) {
        console.log('worker %s écoute sur port %d', worker.id, addr.port);
    });
    cluster.on('disconnect', function(worker) {
        console.log('worker %s déconnecter', worker.id);
    });
    cluster.on('exit', function(worker, code, signal) {
        console.log('worker %s mort (%s)', worker.id, signal || code);
        if (!worker.suicide) {
            console.log('Nouveau worker %s créer', worker.id);
            cluster.fork();
        }
    });
 
//-----------------------------------------
// Since our cluster uses the same node script
// we use an if to check if this process
// is a worker process
//----------------------------------------- 
} else if (cluster.isWorker) {
  startWorker();
}


	
function startWorker() {
	var http = require('http');	
	var express = require('express');
	var app = express();
	var server = app.listen(port);
	var sockets = require('socket.io').listen(server, {'transports': ['polling', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});				// socket.io connexion temps réel entre les clients

	
	console.log('Redis adapter started with url: ' + redisUrl);
	sockets.adapter(redisAdapter({
		pubClient: pub,
		subClient: sub
	}));

	//c'est la page de test
	app.get('/', function(req, res) {
		res.sendFile('index.html', { root: __dirname });
	});
	
	var roomName ='test';
	sockets.on('connection', function(socket) {
		console.log('Client connexion worker: %s', cluster.worker.id);
		//sockets.emit('connection', 'connect');
		socket.room = roomName;
		// connect le client à la room
		socket.join(roomName);
		
		socket.on('chatSendMessage', function(data) {
			//console.log(msg);
			socket.emit('updateChat', data);//à l'emeteur du message
			socket.broadcast.to(roomName).emit('updateChat', 'worker:'+cluster.worker.id+' -> '+data);//au autre client
		});
	  
	});
}
&#13;
&#13;
&#13;

和客户端代码:

&#13;
&#13;
<!doctype html>
<html>
  <head>
    <title>Socket.IO + Cluster 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; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('form').submit(function(){
	  console.log("message : "+$('#m').val());
        socket.emit('chatSendMessage', $('#m').val());
        $('#m').val('');
        return false;
      });
      socket.on('updateChat', function(msg){
        console.log('[CHAT] ' + msg);
        $('#messages').append($('<li>').text(msg));
      });
      socket.on('connection', function(something) {
        $('#messages').append($('<li>').text('connected.'));
        console.log('connected.');
      });
    </script>
  </body>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案