The bus

@param {object} io socket.io instance or http.Server
184190
function Server (a, b) {

  if (!(this instanceof Server)) {
    if (!arguments.length && server) return server;
    var instance = new Server(a, b);
    if (!server) server = instance;
    return instance;
  }


  debug('new server', a, b);

  var self = this;

  events.EventEmitter.call(this);

  /**
   * Called when we are supposed to publish the message. this is bound to a 
   * Builder instance an Receiver instances
   *
   * @api private
   * @param {Message} message
   */

  this.onPublish = function (message) {
    debug('on publish ', message.id());
    self.exchange().publish(message);
  };


  /**
   * Called when we receive a socket connection, this is bound to the
   * socket.io instance
   *
   * @api private
   * @param {Socket} socket
   */

  this.onConnection = function (socket) {

    debug('on connection %s', socket.id);

    function handle (message) {
      debug('from excahnge pubsub %s, %s', message.id(), socket.id);
      self.emit('from exchange pubsub', message, socket);
    }

    self.messages().actor(socket, function (err, actor) {
      if (err) return self.emit('error', err);
      // TODO this could be cleaned up using the alias and unalias methods
      self.exchange().subscribe(actor, handle, function (err, channel) {
        debug('subscribed to chanel %s with socket %s', actor, socket.id);
        if (err) return self.emit('error', err);
      });
      socket.on('disconnect', function () {
        self.exchange().unsubscribe(actor, handle, function (err, channel) {
        debug('unsubscribed from chanel %s with socket %s', actor, socket.id);
          if (err) return self.emit('error', err);
        });
      });
    });

  };

  /**
   * Called when we reeived a message from the Messages.  This is bound
   * to the Messages instance.  It will then emit an event for the
   * SocketReceiver instance to handle. This is when the Messages instance
   * finishes createing the message and before the message is passed along to
   * the Receiver for processing before dispatched to the Exchange.
   *
   * @api private
   * @param {object} message
   * @param {Socket} socket
   * @see Messages
   * @see Receiver
   */

  this.onMessage = function (message, socket) {
    debug('on message from socket %s, %s', (message && message.data ? message.data.id : null), (socket ? socket.id : null));
    if (message.data.action === '_flag') {
      debug('flag set');
      socket._flag = 1;
      return socket.emit('_flag', 1);
    }
    self.emit('from socket', message, socket);
  };

  /**
   * Called after we have received a message from the Exchange
   *
   * @api private
   * @param {Message} message
   * @param {Socket} socket
   * @see Exchange
   * @see Receiver
   */

  this.onReceivedPubSub = function (message, socket) {
    debug('sending message %s to socket %s', (message && message.data ? message.data.id : null), (socket ? socket.id : null));
    if (socket._flag) {
      debug('flag set for bus.io-client');
      socket.emit.apply(socket, [message.data.action, message]);
    }
    else {
      debug('socket.io client');
      socket.emit.apply(socket, [message.data.action, message.data.actor].concat(message.data.content).concat([message.data.target, message.data.created]));
    }
  };

  /**
   * Called after we have received a message from the socket.  This is after
   * the SocketMessage instance creates a message and the Receiver instance
   * processes it through the middleware.
   *
   * @api private
   * @param {Message} message
   * @param {Socket} socket
   * @see Messages
   * @see Receiver
   */

  this.onReceivedSocket = function (message, socket) {
    debug('received a message %s from the socket %s ', (message && message.data ? message.data.id : null), (socket ? socket.id : null));
    self.message(message).deliver();
  };

  /**
   * Called when we receveie a message on the Queue
   *
   * @api private
   * @param {object} message
   * @see Exchange
   */

  this.onReceivedQueue = function (message) {
    debug('received message %s from queue', message.id());
    self.emit('from exchange queue', message);
  };

  /**
   * Handles our error
   *
   * @api private
   * @param {mixed} err
   */

  this.onError = function () {
    debug('on error', arguments);
    console.error.apply(console,Array.prototype.slice.call(arguments));
  };

  this.addListener('error', this.onError);

  this.incomming();

  this.processing();

  this.outgoing();

  this.autoPropagate(true);

  if (a) {
    debug('we have something so we will try to listen to it');
    this.listen(a, b);
  }
}
829804
function EndPoint (local) {
  this.listeners = 0;
  this.dgram = dgram.createSocket('udp4');
  this.dgram.on('message', EndPoint.prototype.receive.bind(this));
  this.dgram.bind(local.port, local.address);
  this.local = this.dgram.address();
  this.packet = new Buffer(2048);
  this.sockets = {};
}
258159
function Socket (options) {
    this.options = {
        port: 80
      , secure: false
      , document: 'document' in global ? document : false
      , resource: 'socket.io'
      , transports: io.transports
      , 'connect timeout': 10000
      , 'try multiple transports': true
      , 'reconnect': true
      , 'reconnection delay': 500
      , 'reconnection limit': Infinity
      , 'reopen delay': 3000
      , 'max reconnection attempts': 10
      , 'sync disconnect on unload': true
      , 'auto connect': true
      , 'flash policy port': 10843
    };

    io.util.merge(this.options, options);

    this.connected = false;
    this.open = false;
    this.connecting = false;
    this.reconnecting = false;
    this.namespaces = {};
    this.buffer = [];
    this.doBuffer = false;

    if (this.options['sync disconnect on unload'] &&
        (!this.isXDomain() || io.util.ua.hasCORS)) {
      var self = this;

      io.util.on(global, 'unload', function () {
        self.disconnectSync();
      }, false);
    }

    if (this.options['auto connect']) {
      this.connect();
    }
}
1013342
function Proxy(proxy) {
  stream.Duplex.call(this);

  this.proxy = proxy ? proxy : { type: 'direct' };

  this.on('error', function () {
    this.push(null);
    this.socket && this.socket.end();
  });
}
950262
function Server (transport) {
	MCS.call(this, transport, DomainMCSPDU.SEND_DATA_REQUEST, DomainMCSPDU.SEND_DATA_INDICATION);
	
	// must be readed from protocol
	this.clientCoreData = null;
	this.clientNetworkData = null;
	this.clientSecurityData = null;
	
	// init gcc information
	this.serverCoreData = gcc.serverCoreData();
	this.serverSecurityData = gcc.serverSecurityData();
	this.serverNetworkData = gcc.serverNetworkData(new type.Component([]));
	
	var self = this;
	this.transport.on('connect', function (selectedProtocol) {
		self.serverCoreData.obj.clientRequestedProtocol.value = selectedProtocol;
	}).once('data', function (s) {
		self.recvConnectInitial(s);
	});
}
367961
function(socket) {
    // Make note of the port numbers for any identd lookups
    // Nodejs < 0.9.6 has no socket.localPort so check this first
    if (typeof socket.localPort !== 'undefined') {
        this.identd_port_pair = socket.localPort.toString() + '_' + socket.remotePort.toString();
        global.clients.port_pairs[this.identd_port_pair] = this;
    }
}
257070
function Client(host, port) {
  this.host = host;
  this.port = port;
  this.socket = null;
  this.connected = false;

  // Useful protocol information
  this.req_counter = 1;
  this.req_table = {};

  this.on_handlers = {
    connect: function() {},
    print_string: function(m) {},
    presentation_start: function (pid) {},
    presentation_end: function (pid) {},
    new_package: function(p) {},
    debug_activate: function(obj) {},
    debug_setup: function(obj) {},
    debug_return: function(obj) {},
    profile_command_complete: function(msg) {},
    disconnect: function() {}
  }

  // Bootstrap the reading state
  this.setup_read(6, this.header_complete_callback);
}
101898
function init(options) {
  options = options || {}
  var port = options.port || 6466
  global.client = global.client || socketIOClient(`http://localhost:${port}`)
  client = global.client
  log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)
  client.emit('join', ioid) // first join for serialization
  client.on('disconnect', client.disconnect)
  client.on('take', hasher.handle) // add listener
  
  // add methods
  client.pass = pass
  client.clientPass = clientPass
  return client
}
594037
function() {
    ws = new SockJS(location.pathname.split("index")[0] + 'socket');
    ws.onopen = function() {
        console.log("CONNECTED");
        if (!inIframe) {
            document.getElementById("footer").innerHTML = "<font color='#494'>"+ibmfoot+"</font>";
        }
        ws.send(JSON.stringify({action:"connected"}));
        onoffline();
    };
    ws.onclose = function() {
        console.log("DISCONNECTED");
        if (!inIframe) {
            document.getElementById("footer").innerHTML = "<font color='#900'>"+ibmfoot+"</font>";
        }
        setTimeout(function() { connect(); }, 2500);
    };
    ws.onmessage = function(e) {
        var data = JSON.parse(e.data);
        //console.log("DATA" typeof data,data);
        if (Array.isArray(data)) {
            //console.log("ARRAY");
            // map.closePopup();
            // var bnds= L.latLngBounds([0,0]);
            for (var prop in data) {
                if (data[prop].command) { doCommand(data[prop].command); delete data[prop].command; }
                if (data[prop].hasOwnProperty("name")) {
                    setMarker(data[prop]);
                    // bnds.extend(markers[data[prop].name].getLatLng());
                }
                else { console.log("SKIP A",data[prop]); }
            }
            // map.fitBounds(bnds.pad(0.25));
        }
        else {
            if (data.command) { doCommand(data.command); delete data.command; }
            if (data.hasOwnProperty("name")) { setMarker(data); }
            else if (data.hasOwnProperty("type")) { doGeojson(data); }
            else {
                console.log("SKIP",data);
                // if (typeof data === "string") { doDialog(data); }
                // else { console.log("SKIP",data); }
            }
        }
    };
}
550914
function Client() {
  EventEmitter.call(this);

  this.debug = false;
  this.socket = dgram.createSocket('udp4');
  this.isSocketBound = false;
  this.devices = {};
  this.port = null;
  this.messagesQueue = [];
  this.sendTimer = null;
  this.discoveryTimer = null;
  this.discoveryPacketSequence = 0;
  this.messageHandlers = [{
    type: 'stateService',
    callback: this.processDiscoveryPacket.bind(this)
  }, {
    type: 'stateLabel',
    callback: this.processLabelPacket.bind(this)
  }, {
    type: 'stateLight',
    callback: this.processLabelPacket.bind(this)
  }];
  this.sequenceNumber = 0;
  this.lightOfflineTolerance = 3;
  this.messageHandlerTimeout = 45000; // 45 sec
  this.resendPacketDelay = 150;
  this.resendMaxTimes = 5;
  this.source = utils.getRandomHexString(8);
  this.broadcastAddress = '255.255.255.255';
}
557995
function MasterNode(io, config, pass) {
  EventEmitter.call(this);
  this.connected = [];  // array of connected clients.
  this.disconnected = []; // an array of disconnected and removed clients.
  this.disconnecting = [];  //array of disconnecting clients (didn't reconnect within 10sec)
  this.io = io;
  this.config = config;
  this.config.password = crux.util.sha2(pass);
  this.__loadDump();
  this.bind();
}
120353
function SocketClient (socket) {
    var that = this;

    this.socket = socket;
    this.socket_closing = false;

    this.remoteAddress = this.socket.remoteAddress;
    winston.info('Control connection from %s opened', this.socket.remoteAddress);

    this.bindEvents();

    socket.write("\nHello, you are connected to the Kiwi server :)\n\n");

    this.control_interface = new ControlInterface(socket);
    _.each(socket_commands, function(fn, command_name) {
        that.control_interface.addCommand(command_name, fn.bind(that));
    });
}
540027
function Pubsub(bus, name) {
  events.EventEmitter.call(this);
  this.bus = bus;
  this.type = 'pubsub';
  this.id = "bus:pubsub:" + name;
  this.logger = bus.logger.withTag(this.id);
  this.name = name;
}
868202
function socketClient(serviceUrl) {
  var self = object.create(socketClient.prototype);
  var urlObject = url.parse(serviceUrl);

  // create the url without the path
  var socketIoUrl = url.format({
    protocol: urlObject.protocol,
    hostname: urlObject.hostname
  });

  var options = {
    reconnection: true,
    reconnectionDelay: 1000,
    reconnectionDelayMax: 50000,
    reconnectionAttempts: 5,
    autoConnect: false,
    path: url.clearTraliningSlash(urlObject.path) + '/socket.io/'
  };

  self.socket = io(socketIoUrl, options);
  self.opened = false;

  return self;
}
411644
function Channel(bus, name, local, remote) {
  events.EventEmitter.call(this);
  this.bus = bus;
  this.name = name;
  this.type = 'channel';
  this.id = 'bus:channel:' + name;
  this.logger = bus.logger.withTag(name);
  this.local = local || 'local';
  this.remote = remote || 'remote';

  this.handlers = {
    '1': this._onRemoteConnect,
    '2': this._onMessage,
    '3': this._onRemoteDisconnect,
    '4': this._onEnd
  }
}
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}
735398
function ServerConnection (options) {

    this.log = options.log;
    this.port = options.port;
    this.proxyUrl = options.proxyUrl;

    if (!(options.udp4 === false)) {
        this.listenUDP4();
    }
    if (!(options.tcp === false)) {
        this.listenTCP();
    }
    if (!(options.socketio === false)) {
        this.listenSocketIO();
    }

    EventEmitter.call(this);

}