NodeJS Socket Broadcast

var net=require(‘net‘);
var host=‘192.168.0.201‘;

function executeCommand(socket, command, args) { 
    var json = {};
    switch(command){
      case "01":
      case "02":
        json.beaconid = args;
        json.state = command;
        result = JSON.stringify(json);
        console.log(‘server:‘+result);
        socket.write(‘server:‘+result);
        cs.write(‘client:‘+result);
        break;
    }
};

clientList = [];

function broadcast(message, client) {
  var cleanup = [];
  for(var i=0;i<clientList.length;i++) {
    if(client !== clientList[i]) {
      if(clientList[i].writable) { 
        clientList[i].write(message);
      } else {
        cleanup.push(clientList[i]);
        clientList[i].destroy();
      }

    }
  }

  for(i=0;i<cleanup.length;i++) {
      clientList.splice(clientList.indexOf(cleanup[i]), 1);
  }
}

var c = net.createServer(function(socket){
    socket.on(‘data‘, function(d) { 
      data = d.toString(‘utf8‘).trim();
      console.log(data);  
      broadcast(data, socket);
    });

    socket.on(‘end‘, function() {
      console.log(‘client server disconnected‘);
      try{
        clientList.splice(clientList.indexOf(client), 1);
      }catch(ex){}
    });

    socket.on(‘error‘, function (ex) {
      console.log("client ignoring exception: " + ex);
    });
});

c.on(‘connection‘, function(client) {
  client.name = client.remoteAddress + ‘:‘ + client.remotePort
  //client.write(‘Hi ‘ + client.name + ‘!\n‘);
  clientList.push(client);
})

c.listen(2222,host);
console.log(‘client listen on ‘ + host + ‘,port:2222...‘);
var cs = net.connect({port: 2222,host:host});

var s = net.createServer(function(socket) {
    console.log(‘server connected‘);

    socket.on(‘data‘, function(d) { 
      data = d.toString(‘utf8‘).trim();  
      var cmd_re = /^(\d{2})+[ ]*(.*)/g;
      cmd_match = cmd_re.exec(data)  
      if (cmd_match) {  
        var command = cmd_match[1];  
        var args = cmd_match[2];  
        console.log(command+" "+args);
        executeCommand(socket, command, args);  
      } 
    });

    socket.on(‘end‘, function() {
      console.log(‘server disconnected‘);
    });

    socket.on(‘error‘, function (ex) {
      console.log("ignoring exception: " + ex);
    });

});  
s.listen(1111,host);
console.log(‘server listen on ‘ + host + ‘,port:1111...‘);

 Ref:学习 NodeJS 第八天:Socket 通讯

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。