all files / commanders/web/ web-socket.js

21.62% Statements 8/37
0% Branches 0/6
0% Functions 0/9
21.62% Lines 8/37
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 52 53 54 55 56                                                                                                
var WebSocketServer = require('ws').Server;
// 连接池
var clients = [];
var staticParams = {};
 
exports.broadcast = function broadcast(message) {
  clients.forEach(function(ws1) {
    cml.log.debug('[web liveload send] ' + message)
    try {
      ws1.send(message);
    } catch (e) {
      cml.log.debug('[web liveload] broadcast err')
      let index = clients.indexOf(ws1);
      if (index !== -1) {
        clients.splice(index, 1);
      }
    }
  })
}
 
 
exports.startServer = function startServer (options) {
  const server = options.server;
  var wss = new WebSocketServer({server});
  wss.on('connection', function(ws) {
    clients = [];
    clients.push(ws);
    exports.initRouter();
    ws.on('close', function(message) {
      cml.log.debug('[web liveload] close');
    });
  });
}
exports.initRouter = function initRouter() {
  let routeList = exports.getRouteConfig();
  exports.broadcast(routeList);
}
exports.getRouteConfig = function getRouteConfig() {
  let {routerConfig, hasError} = cml.utils.getRouterConfig();
  if (!hasError) {
    routerConfig = Object.assign(routerConfig, staticParams);// {jsbundle,subpath}
    return JSON.stringify(routerConfig);
  }
}
exports.createRoutesReact = function createRoutesReact(options) {
  staticParams = options.staticParams;
  exports.startServer(options);
  cml.event.removeAllListeners('routerchange');
  cml.event.on('routerchange', function() {
    let routeList = exports.getRouteConfig();
    if (routeList) {
      exports.broadcast(routeList)
    }
  })
}