Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

用cluster的master可以共享多个worker的全局数据吗?

$
0
0

比如数据保存在一个全局变量 var message里 这样多个woker和 master都同时读写这个数据会不会出错呢? app.js

var cluster = require('cluster');
var io = require('socket.io')();
var numCPUs = require('os').cpus().length;
console.log(' numCPUs is ',numCPUs);
var connections=0;
if (cluster.isMaster) {
   console.log("master start...");

   // Fork workers.
   for (var i = 0; i < numCPUs; i++) {
       cluster.fork();
   }

   cluster.on('listening',function(worker,address){
       console.log('[Master ]listening: worker ' + worker.process.pid +', Address: '+address.address+":"+address.port);
   });

   cluster.on('exit', function(worker, code, signal) {
       console.log('[Master]  worker exit ' + worker.process.pid + ' died');
   });
} else if (cluster.isWorker) {



   io.on('connection', function(socket) {

      console.log('this is process',process.pid);
     connections++;

      console.log("client ++",connections);


      socket.on('disconnect', function() {
 connections--;
   console.log("client --",connections);
      });

     socket.on('message',function (msg) {
     	console.log(msg);
     	 
     });

   });
io.listen(9000);


}



test.html

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>
		
	</title>
	<script src="/js/socket.io.js"></script>
</head>
<body>
	



<script type="text/javascript">


var socket = io.connect('ws://localhost:9000',{'reconnection':true});


socket.on('message', function(msg){

  console.log(msg);

});


 socket.emit('message',{foo:11,bar:22});
 

</script>

</body>
</html>

这样启动app.js ,用第一个浏览器刷页面,能看到 控制台显示 client ++ 但是第二个浏览器刷页面,没有反应


Viewing all articles
Browse latest Browse all 14821

Trending Articles