all files / commanders/weex/ socket-server.js

22.22% Statements 6/27
0% Branches 0/2
0% Functions 0/7
22.22% Lines 6/27
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                                                                          
var WebSocketServer = require('ws').Server;
var utils = require('../../configs/utils.js');
 
// 连接池
var clients = [];
 
function broadcast(message) {
  clients.forEach(function(ws1) {
    cml.log.debug('[weex liveload send] ' + message)
    try {
      ws1.send(message);
    } catch (e) {
      cml.log.debug('[weex liveload] broadcast err')
      let index = clients.indexOf(ws1);
      if (index !== -1) {
        clients.splice(index, 1);
      }
    }
  })
}
 
 
function startServer (options) {
  var port = utils.getFreePort().weexLiveLoadPort;
  var wss = new WebSocketServer({port: port});
  cml.log.debug('start weex liveload at port:' + port);
  wss.on('connection', function(ws) {
    cml.log.debug('[weex liveload] connection')
    // 将该连接加入连接池
    clients.push(ws);
    ws.on('message', function(message) {
      cml.log.debug('[weex liveload] message');
      cml.log.debug(message);
    });
 
    ws.on('close', function(message) {
      cml.log.debug('[weex liveload] close');
 
      // 连接关闭时,将其移出连接池
      clients = clients.filter(function(ws1) {
        return ws1 !== ws
      })
    });
  });
}
 
module.exports = {
  startServer,
  broadcast
}