_________________________________ CLIENT/SERVER
199959
function(context, descriptor, args, stack) {
		if (context.env.data.isServer)
			return;
		secondPass(args[0], context, descriptor, stack);
	}
1111974
function initClient (args) {
    // create client configuration
    this.client = {
        binds: [],
        hooks: {},
        minify: false,
        placeholders: {},
        refreshInterval: 0,
        server: {
            hasGet: defined(this.module.get),
            hasSet: defined(this.module.set),
        }
    }
    // skip if client args not set
    if (!defined(args.client)) {
        return
    }
    // add any hooks
    _.each(args.client.hooks, (hook, name) => {
        // require function
        this.assert(typeof hook === 'function', 115)
        // require valid hook
        this.assert(hookNames[name], 116, `${name} is not a valid hook name`)
        // set hook
        this.client.hooks[name] = hook
    })
    // set refresh interval if defined
    if (defined(args.client.refreshInterval)) {
        // convert to integer
        var refreshInterval = parseInt(args.client.refreshInterval)
        // require positive integer
        this.assert(refreshInterval > 0, 117)
        // set refresh interval
        this.client.refreshInterval = refreshInterval
    }
    // set binds if defined
    if (defined(args.client.binds)) {
        // require object, can be array
        this.assert(args.client.binds && typeof args.client.binds === 'object', 118)
        // store binds
        this.client.binds = args.client.binds
    }
    // set any client boolean options
    _.each(clientOptions, option => {
        if (defined(args.client[option])) {
            this.client[option] = !!args.client[option]
        }
    })
    // add any placeholders if defined
    _.each(args.client.placeholders, (value, property) => {
        this.client.placeholders[property] = value
    })
}
1136051
private function initServer() {
        $this->http = new Object();
        $this->server = new Object();

        foreach ($_SERVER as $key => $val) {
            $key = str_replace('request_', '', strtolower($key));
            if (substr($key, 0, 5) === 'http_') {
                $this->http->{Util::_toCamel(substr($key, 5))} = $val;
            }
            elseif (substr($key, 0, 7) === 'server_') {
                $this->server->{Util::_toCamel(substr($key, 7))} = $val;
            }
            else {
                $this->{Util::_toCamel($key)} = $val;
            }
        }
    }
662729
function Context() {
	/**
	 * @member {Object}
	 * @property {Object} client
	 * @property {Object<Call>} client.map - map from call name and call id
	 * @property {Array<Call>} client.list
	 * @property {Object} server
	 * @property {Object<Call>} server.map - map from call name and call id
	 * @property {Array<Call>} server.list
	 * @private
	 */
	this._calls = {
		client: {
			map: Object.create(null),
			list: []
		},
		server: {
			map: Object.create(null),
			list: []
		}
	}

	/**
	 * @member {Object}
	 * @property {Object} client
	 * @property {Object<Message>} client.map - map from message name and message id
	 * @property {Array<Message>} client.list
	 * @property {Object} server
	 * @property {Object<Message>} server.map - map from message name and message id
	 * @property {Array<Message>} server.list
	 * @private
	 */
	this._messages = {
		client: {
			map: Object.create(null),
			list: []
		},
		server: {
			map: Object.create(null),
			list: []
		}
	}
}
343940
function createServer(listen, opt) {

  if (!listen) {
    throw new TypeError('listen required');
  }
  var options = opt || Object.create(null);
  var my = {
    keepalive: Number(options.keepalive) || 2000,
    callback: typeof options.callback === 'function' ? options.callback : false,
    http: false,
    https: false
  };
  if (typeof options.http === 'object') {
    my.http = {
      port: Number(options.http.port) || 3000,
      host: String(options.http.host || '127.0.0.1')
    };
  }
  if (typeof options.https === 'object') {
    my.https = options.https;
    my.https.port = Number(options.https.port) || 3000;
    my.https.host = String(options.https.host || '127.0.0.1');
  }

  var hosts = Object.create(null);
  var server = net.createServer(function(sock) {

    sock.setKeepAlive(true, my.keepalive); // https://en.wikipedia.org/wiki/Keepalive
    sock.on('data', function(buff) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      } else if (buff.length > 1) { // set client id
        var _id = String(buff);
        hosts[_id] = {
          state: sock.readyState,
          beat: Date.now()
        };
        sock._id = _id;
      }
      return;

    }).on('close', function(had_error) {

      if (sock._id) {
        hosts[sock._id] = {
          state: sock.readyState,
          beat: Date.now()
        };
      }
      // error hook [with client id]
      return my.callback !== false ? my.callback(had_error, sock._id) : null;
    });
  });

  if (options.host && typeof listen === 'number') { // tpc only
    server.listen(listen, options.host);
  } else {
    server.listen(listen);
  }

  if (my.http || my.https) {
    var web = function(req, res) {

      var out = '';
      res.setHeader('Content-Type', 'application/json; charset=utf-8');
      var url = decodeURI(req.url);
      url = url.substr(1, url.length);
      if (url === '') {
        out = JSON.stringify(hosts);
      } else if (hosts[url] !== undefined) {
        out = JSON.stringify(hosts[url]);
      } else {
        res.statusCode = 404;
      }
      return res.end(out);
    };
    if (my.http) {
      require('http').createServer(web).listen(my.http.port, my.http.host);
    }
    if (my.https) {
      require('https').createServer(my.https, web).listen(my.https.port,
        my.https.host);
    }
  }

  server._hosts = hosts; // hosts reference
  return server;
}
822770
function (server, version, socket, options) {
  var self = this;
  self.id = Random.id();

  self.server = server;
  self.version = version;

  self.initialized = false;
  self.socket = socket;

  // set to null when the session is destroyed. multiple places below
  // use this to determine if the session is alive or not.
  self.inQueue = [];

  self.blocked = false;
  self.workerRunning = false;

  // Sub objects for active subscriptions
  self._namedSubs = {};
  self._universalSubs = [];

  self.userId = null;

  self.collectionViews = {};

  // Set this to false to not send messages when collectionViews are
  // modified. This is done when rerunning subs in _setUserId and those messages
  // are calculated via a diff instead.
  self._isSending = true;

  // If this is true, don't start a newly-created universal publisher on this
  // session. The session will take care of starting it when appropriate.
  self._dontStartNewUniversalSubs = false;

  // when we are rerunning subscriptions, any ready messages
  // we want to buffer up for when we are done rerunning subscriptions
  self._pendingReady = [];

  // List of callbacks to call when this connection is closed.
  self._closeCallbacks = [];


  // XXX HACK: If a sockjs connection, save off the URL. This is
  // temporary and will go away in the near future.
  self._socketUrl = socket.url;

  // Allow tests to disable responding to pings.
  self._respondToPings = options.respondToPings;

  // This object is the public interface to the session. In the public
  // API, it is called the `connection` object.  Internally we call it
  // a `connectionHandle` to avoid ambiguity.
  self.connectionHandle = {
    id: self.id,
    close: function () {
      self.close();
    },
    onClose: function (fn) {
      var cb = Meteor.bindEnvironment(fn, "connection onClose callback");
      if (self.inQueue) {
        self._closeCallbacks.push(cb);
      } else {
        // if we're already closed, call the callback.
        Meteor.defer(cb);
      }
    },
    clientAddress: self._clientAddress(),
    httpHeaders: self.socket.headers
  };

  socket.send(stringifyDDP({msg: 'connected',
                            session: self.id}));
  // On initial connect, spin up all the universal publishers.
  Fiber(function () {
    self.startUniversalSubs();
  }).run();

  if (version !== 'pre1' && options.heartbeatInterval !== 0) {
    self.heartbeat = new Heartbeat({
      heartbeatInterval: options.heartbeatInterval,
      heartbeatTimeout: options.heartbeatTimeout,
      onTimeout: function () {
        self.close();
      },
      sendPing: function () {
        self.send({msg: 'ping'});
      }
    });
    self.heartbeat.start();
  }

  Package.facts && Package.facts.Facts.incrementServerFact(
    "livedata", "sessions", 1);
}
1233361
function(client, msg, serverType, serverId, cb) {
  if (typeof serverId !== 'string') {
    logger.error('[omelo-rpc] serverId is not a string : %s', serverId);
    return;
  }
  if (serverId === '*') {
    let servers = client._routeContext.getServersByType(serverType);
    if (!servers) {
      logger.error('[omelo-rpc] serverType %s servers not exist', serverType);
      return;
    }

    async.each(servers, function(server, next) {
      let serverId = server['id'];
      client.rpcInvoke(serverId, msg, function(err) {
        next(err);
      });
    }, cb);
  } else {
    client.rpcInvoke(serverId, msg, cb);
  }
}
36898
def server_data
      if name == :origen
        @server_data ||= Origen.client.origen
      else
        @server_data ||= Origen.client.plugins.find { |p| p[:origen_name].downcase == name.to_s.downcase }
      end
    end
563780
function (options, callbackFn) {
            var self = this;

            //compensate for optional options parm
            if (typeof options === 'function') {
                callbackFn = options;
                options = {};
            }

            //assign default port
            options.port = options.port || 1061;
            options.host = options.host || 'localhost';
            options.hostAndPort = 'http://' + options.host + ':' + options.port;
            options.eventStreamPath = require('path').normalize(__dirname + '/../temp/events.txt');
            options.phantomjsPath = options.phantomjsPath || 'phantomjs';

            options.debug && console.log('creating proxy to %s', options.hostAndPort);

            this.options = options;

            //try starting server
            createServer.call(self, options, function (proxy) {
                callbackFn.call(self, proxy);
            });

            return this;//return this to chain end
        }
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);
  }
}
1243681
function startServer() {
    http.createServer((req, res) => {
        const fileName = __dirname + path.sep + new Date().getTime() + '.png';

        req.on('end', () => {
            res.writeHead(200);
            res.end();

            fs.stat(fileName, function(error, stat) {
              console.log(
                'Stored file ' + fileName +
                ' with size ' + stat.size +
                ', headers: ' + JSON.stringify(req.headers)
              );
              fs.unlinkSync(fileName);
            });
        });
        req.pipe(fs.createWriteStream(fileName));
    }).listen(DEF_CLIENT_PORT);

    console.log("Client server running on port 8124");
}
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';
}
743348
function Client(opts) {
    if (!(this instanceof Client)) {
        return new Client(opts);
    }

    var options = {};

    // If single connection provided, array-ify it
    if (typeof opts === 'string') {
        options.hosts = [opts];
        opts = options;
    } else if (typeof opts === 'undefined') {
        opts = {};
    } else if (_.isArray(opts)) {
        options.hosts = opts;
        opts = options;
    }

    _.defaults(opts, {
        autodiscover: false,
        bufferBeforeError: 1000,
        disabled: false,
        hosts: null,
        reconnect: true,
        onNetError: function onNetError(err) { console.error(err); },
        queue: true,
        netTimeout: 500,
        backoffLimit: 10000,
        maxValueSize: 1048576
    });

    // Iterate over options, assign each to this object
    R.keys(opts).forEach(function(key) {
        this[key] = opts[key];
    }, this);

    if (this.queue) {
        this.buffer = new Immutable.List();
    }

    debug('Connect options', opts);
    this.connect();
}
675127
function Client(rwStream, options)
{
	events.EventEmitter.call(this);
	
	var tidCounter = 0;
	var requestMap = {};
	var isClosed = true;
	var address = '';
	var host = '';
	
	var idlePingTimeout 	= getOption(options, 'idlePingTimeout',		0);
	var idleCloseTimeout	= getOption(options, 'idleCloseTimeout',	0);
	var autoRegister		= getOption(options, 'autoRegister', 		false);
	var logConnection		= getOption(options, 'logConnection', 		true);
	var autoResponseUnhandledCommand = getOption(options, 'autoResponseUnhandledCommand', true);
	
	this.isServer = options.isServer;
	
	function getAddress()
	{
		return util.format('%s:%s', rwStream.remoteAddress.replace(/^::ffff:/i, ''), rwStream.remotePort);		
	}
	
	function log(event)
	{
		if ( logConnection )
		{
			console.log(util.format('%s %s(%s)', event, host, address));
		}
	}
	
	this.closeStream = function() {

		//console.log('isClosed ' + isClosed);
		
		if ( !isClosed )
		{
			isClosed = true;
			
			log('CLOSE');
			
			if ( rwStream instanceof stream.Writable )
			{
				rwStream.end();
			}
		
			for ( var tid in requestMap )
			{
				if ( requestMap.hasOwnProperty(tid) )
				{
					clearTimeout(requestMap[tid].timer);
					requestMap[tid].callback({code: '500', tid: tid, args: ['socket_closed'], body: null, isValid: true});
					delete requestMap[tid];
				}
			}
			
			this.emit('close');
		}
	};
	
	if ( rwStream instanceof stream.Writable )
	{
		this.sendMessage = function(code, tid, args, body, callback) {
			var bodyBuf = Buffer.isBuffer(body) ? body : 
				typeof(body) === 'string' ? Buffer.from(body) : 
					null;
			tid = tid === -1 ? ++tidCounter : tid;
			tid = '' + tid;
			var bodyLen = bodyBuf ? bodyBuf.length : 0;
			var header = util.format('%s %s %d%s\r\n', code, tid, bodyLen, encodeArgs(args));
			var headerLen = Buffer.byteLength(header);
			var msg = {code: code, tid: tid, args: args, body: body};
			if ( options.debugHeader )
			{
				console.log("send msg: %s", msg2str(msg));
			}
			rwStream.write(header, callback);
			if ( bodyLen > 0 )
			{
				rwStream.write(bodyBuf);
			}
		};

		this.sendRequest = function(code, args, body, timeout, callback) {
			var tid = ++tidCounter;
			this.sendMessage(code, tid, args, body);
			requestMap[tid] = {
				callback: callback,
				timer: setTimeout(() => this.emit('message_timeout', tid), timeout)
			};
		};
	}
	
	if ( rwStream instanceof stream.Readable )
	{
		var parser = textParser.createParser((msg) => {

			if ( options.debugHeader )
			{
				console.log("recv msg: %s", msg2str(msg));
			}

			if ( !msg.isValid && this.sendMessage )
			{
				this.sendMessage('201', 0, 'invalid_command');
			}
			else
			{
				if ( /^\d+$/.test(msg.code) )
				{
					var tid = msg.tid !== null && /^\d+$/.test(msg.tid) ? msg.tid * 1 : 0;
					
					if ( tid > 0 )
					{
						if ( requestMap.hasOwnProperty(msg.tid) )
						{
							clearTimeout(requestMap[msg.tid].timer);
							requestMap[msg.tid].callback(msg);
							delete requestMap[msg.tid];
						}
						else
						{
							console.log(util.format('ERR dangling response: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
						}
					}
					else
					{
						console.log(util.format('ERR invalid tid: %s %s [%s]', msg.code, msg.tid, msg.args.join(' ')));
					}
				}
				else
				{
					var isHandled = false;
					
					if ( this.listenerCount(msg.code) > 0 )
					{
						isHandled = true;
						this.emit(msg.code, msg);
					}
					
					if ( this.listenerCount('message') > 0 )
					{
						isHandled = true;
						this.emit('message', msg);
					} 
					
					if ( !isHandled && autoResponseUnhandledCommand && this.sendMessage )
					{
						this.sendMessage('201', msg.tid, 'unknown_command');
					}
				}
			}
		});
		
		rwStream.on('data', (data) => {
			parser.feed(data);
		});
		
		rwStream.on('end', (e) => {
			this.closeStream();
		});
	}
	
	if ( rwStream instanceof net.Socket )
	{
		if ( !rwStream.connecting )
		{
			this.address = address = getAddress();
			isClosed = false;
			log('ACCEPT');
		}

		if ( idlePingTimeout > 0 )
		{
			rwStream.setTimeout(idlePingTimeout);
		}
		else if ( idleCloseTimeout > 0 )
		{
			rwStream.setTimeout(idleCloseTimeout);
		}
		
		rwStream.on('timeout', () => {
			if ( idlePingTimeout > 0 )
			{
				this.sendMessage('PING', 0, [], null);
				log('PING');
			}
			else if ( idleCloseTimeout > 0 )
			{
				this.closeStream();
			}
			else
			{
				this.emit('timeout');
			}
		});
		
		rwStream.on('connect', () => {
			this.address = address = getAddress();
			isClosed = false;
			log('CONNECT');
			if ( autoRegister )
			{
				this.sendMessage('RGST', 0, os.hostname());
				log('RGST');
			}
			this.emit('connect');
		});
		
		rwStream.on('close', (had_error) => {
			this.closeStream();
		});
		
		this._getSessionManager = function() {
			if ( !this.sessionManager )
			{
				this.sessionManager = new SessionManager(this, options);
			}
			return this.sessionManager;
		};
		
		this.onSession = function(protocol, callback) {
			var smgr = this._getSessionManager();
			var listener_options = Object.assign({}, options, {protocol: protocol});
			var slnr = new SessionListener(listener_options);
			slnr.on('session', callback);
			smgr.registerListener(slnr);
		};
		
		this.createSession = function(protocol, session_args) {
			var smgr = this._getSessionManager();
			var session_options = Object.assign({}, options, {protocol: protocol, session_args: session_args});
			return smgr.createSession(session_options);
		};
	} 
	
	rwStream.on('error', (e) => {
		log('ERROR ' + e.message);
		this.closeStream();
		this.emit('error', e);
	});
	
	this.on('message_timeout', (tid) => {
		if ( requestMap.hasOwnProperty(tid) )
		{
			requestMap[tid].callback({code: '500', tid: tid, args:['message_timeout'], body: null, isValid: true});
			delete requestMap[tid];
		}
	});
	
	this.on('RGST', (msg) => {
		host = msg.args.length > 0 ? msg.args[0] : '';
		log('RGST');
	});
	
	this.on('PING', (msg) => {
		log('PING');
	});
}
889412
async function main() {
  event.$emit('before-client-render')

  if (globalState.initialData) {
    dataStore.replaceState(globalState.initialData)
  }

  await routerReady(router)

  if (router.getMatchedComponents().length === 0) {
    throw new ReamError(pageNotFound(router.currentRoute.path))
  }
}
1313226
function createServer(serverName) {
        console.log("creating server", serverName)
        var server = servers[serverName] = net.createServer(handleConnection)
        ports.service(serverName, listen)

        function handleConnection(connection) {
            console.log("got incoming connection", connection)
            var stream = proxy.connect(serverName)
                , buffer = PauseStream().pause()
                , intermediate = through(stringer)

            connection.pipe(buffer)

            process.nextTick(pipe)

            function pipe() {
                buffer.pipe(intermediate)
                    .pipe(stream).pipe(connection)

                buffer.resume()
            }
        }

        function listen(port, ready) {
            server.listen(port, ready)
        }
    }
1123948
function resolveServer(path, options) {
    if (options === void 0) { options = {}; }
    var serverUrl = options.serverUrl || init.initOptions.serverUrl;
    if (path) {
        if (serverUrl) {
            path = url.resolve(serverUrl, path);
        }
    }
    else {
        path = serverUrl;
    }
    return url.resolve(path, '/');
}