Connection(s) handler (Socket, SockJS)
163796
function handleConnection(conn, conf, appParams)
{
    var requiredApp = null;
    var runningApp = null;
    var runningAppID = null;
    var buffer = "";

    // console.log("New connection from [" + conn.remoteAddress + "]");

    conn.on('data', function (message)
    {
        var pkg;
        var strMessage = buffer + message.toString();
        pkg = strMessage.split("\n");

        if (strMessage.substr(-1) !== "\n")
        {
            buffer = pkg.pop();
        }

        pkg.map(function (jsonPkg)
        {
            if (jsonPkg.length < 2)
            {
                return;
            }

            var o = JSON.parse(jsonPkg);
            switch (o["a"])
            {
                case "x":
                    // if the alias exists: executes it
                    if (conf["aliases"] && conf["aliases"][o["w"]])
                    {
                        var tmpLog = "Starting [" + o["w"] + "] ...";
                        try
                        {
                            requiredApp = r_equire(global.__base_path + conf["aliases"][o["w"]]);
                            tmpLog += "OK!";

                            runningApp = requiredApp({
                                "send": function (m)
                                {
                                    conn.write(m);
                                },
                                "close": function ()
                                {
                                    runningApp.app.destroyAll();
                                    conn.close();
                                }
                            }, appParams);
                        }
                        catch (e)
                        {
                            requiredApp = null;
                            runningApp = null;
                            tmpLog += "ERROR [" + e + "]!";
                        }

                        if (runningApp !== null)
                        {
                            // registers the app
                            runningAppID = registerRunningApp(runningApp);
                            // enables the broadcasting
                            injectBroadcasting(runningApp);
                        }

                        console.log(tmpLog);
                    }
                    else
                    {
                        console.log('Error: Alias [' + o["w"] + '] not found!');
                    }
                    break;
                default:
                    // packages handled by the app itself
                    runningApp && runningApp.parseRequests(o);
            }

        });

    });
    conn.on('close', function ()
    {
        runningApp && runningApp.onClose();

        if (runningAppID !== null)
        {
            unregisterRunningApp(runningAppID);
        }
    });
    conn.on('error', function ()
    {
        runningApp && runningApp.onError();

        console.log("Connection ERROR!!!");
    });
}
1060401
function listen() {
  var args = []
    , port = this.conf.get(ConfigKey.PORT)
    , socket = this.conf.get(ConfigKey.UNIXSOCKET)
    , perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
    , backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
    , cb = typeof arguments[arguments.length - 1] === 'function'
      ? arguments[arguments.length - 1] : null
    , tcp
    , unix;

  if(socket) {
    unix = this._unix = new UnixServer(this);
  }

  // tcp: server.listen(port, [host], [backlog], [callback])
  // unix socket: server.listen(path, [callback])

  // port zero means don't listen on a tcp port
  if(port !== 0) {
    tcp = this._tcp = new TcpServer(this);

    // port comes first
    args.unshift(port);

    // backlog is penultimate argument
    if(typeof backlog === 'number') {
      args.push(backlog);
    }

    //console.dir(args);

    // cb is last argument
    if(cb) args.push(cb);

    function onListen() {
      // for server info, the actual port or socket in use
      // stored on the state, null if listen was never called
      // or if the bind failed, could also be a unix socket
      var addr = tcp.address();
      var port = addr.port;
      this.state.addr = addr;

      // only write pid if we listen
      if(this._daemonized) {
        daemon.pid.write(this.conf);
      }

      this.emit('listen', port);
      this.log.notice('accepting connections on port %s', port);

      // might be listening on a unix socket too
      if(unix) unix.listen(socket, perm);
    }

    tcp.once('listening', onListen.bind(this));
    tcp.listen.apply(tcp, args);
  // just a unix socket
  }else if(unix) {
    unix.listen(socket, perm);
  }
}
1069365
function Connection(socket, pool) {
    _classCallCheck(this, Connection);

    this.socket = socket;
    this.id = socket.id;
    this.pool = pool;
    this.incomingFilters = [];
  }
752492
def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):
    
    ssh_version = subprocess.check_output(['ssh', '-V'],
                                          stderr=subprocess.STDOUT)
    log.debug('local SSH version: %r', ssh_version)
    environ = {'SSH_AUTH_SOCK': sock_path, 'SSH_AGENT_PID': str(os.getpid())}
    device_mutex = threading.Lock()
    with server.unix_domain_socket_server(sock_path) as sock:
        sock.settimeout(timeout)
        quit_event = threading.Event()
        handle_conn = functools.partial(server.handle_connection,
                                        handler=handler,
                                        mutex=device_mutex)
        kwargs = dict(sock=sock,
                      handle_conn=handle_conn,
                      quit_event=quit_event)
        with server.spawn(server.server_thread, kwargs):
            try:
                yield environ
            finally:
                log.debug('closing server')
                quit_event.set()
1119306
def yield_connections(sock):
    """"""
    while True:
        log.debug('waiting for connection on %s', sock.getsockname())
        try:
            conn, _ = sock.accept()
        except KeyboardInterrupt:
            return
        conn.settimeout(None)
        log.debug('accepted connection on %s', sock.getsockname())
        yield conn
936311
function Socket(/* [options] */) {
    events.EventEmitter.call(this);
    var self = this;

    // Socket
    if (arguments[0] instanceof net.Socket) {
        this._socket = arguments[0];
    } else {
        var options = arguments[0] || {};
        this._socket = new net.Socket(options);
    }
    
    // Configuration
    this.signature = 174021652;

    // Read data
    this._buffers = [];
    this._offset = 0;            // Current offset in the first buffer    
    this._length = 0;            // Sum of all buffers minus offset
    this._messageLength = null;

    // Write data
    this._header = new Buffer(8);
    this._header.writeUInt32BE(this.signature, 0);

    // Event handlers
    this._socket.on('data', this.onData.bind(this));

    // Relay some of the socket events that don't need to be handled
    [   'connect',
        'end',
        'close',
        'timeout',
        'drain',
        'error'
    ].forEach(function (event) {
        self._socket.on(event, function (data) {
            self.emit(event, data);
        });
    });

    // Relay some of the socket properties that don't need to be handled
    [   'remoteAddress',
        'remotePort',
        'bytesRead',
        'bytesWritten',
        'bufferSize'
    ].forEach(function (propertyName) {
        Object.defineProperty(self, propertyName, {
            get: function () {
                return self._socket[propertyName];
            },
            enumerable: true
        });
    });

    // Relay some of the socket functions that don't need to be handled
    [   'connect',
        'destroy',
        'pause',
        'resume',
        'setTimeout',
        'setNoDelay',
        'setKeepAlive',
        'address'
    ].forEach(function (functionName) {
        self[functionName] = function () {
            return self._socket[functionName].apply(self._socket, arguments);
        };
    });
}
171313
function connection(socket, server) {
  var conn = new Connection(socket)
    , tcp = (server instanceof TcpServer);

  var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
  if(maxclients && (this.state.length + 1 > maxclients)) {

    this.state.emit('rejected', conn.client.addr, maxclients);

    this.log.debug('rejected %s, exceeds maxclients %s',
      conn.client.addr, maxclients);

    function onWrite() {
      socket.end();
    }

    return conn.write(MaxClients, onWrite.bind(this));
  }

  if(tcp) {
    this.log.debug('accepted connection from %s', conn.client.addr);
  }else if(server) {
    this.log.debug('accepted connection to %s', server.name);
  }else if(!server) {
    this.log.debug('accepted connection in %s', process.pid);
  }

  var timeout = this.conf.get(ConfigKey.TIMEOUT);
  if(typeof timeout === 'number' && timeout) {
    this.log.debug('setting idle timeout for client #%s to %ss',
      conn.id, timeout);
    // config is seconds, socket want milliseconds
    socket.setTimeout(timeout * 1000, function onTimeout() {
      // TODO: log client connection timeout
      socket.destroy();
    })
  }

  conn.once('disconnect', this.disconnect.bind(this));
  conn.on('command', this.command);
  this._state.addConnection(conn);
}
740232
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler:
        
        return ConnectionHandler("https", "wss", self.server, self.port, "", session, proxy)
420021
function WebsocketConnection(socket, url) {
  this.socket = socket;
  this.url = url;

  this.deferreds = {};
  this.nextRequestId = 0;

  this.onReply = this.onReply.bind(this);
  this.onEvent = this.onEvent.bind(this);
}
155750
public void handleConnection(Socket socket) throws IOException
    {
        // Check acceptable remote servers
        if (_remoteServers!=null&&_remoteServers.length>0)
        {
            boolean match=false;
            InetAddress inetAddress=socket.getInetAddress();
            String hostAddr=inetAddress.getHostAddress();
            String hostName=inetAddress.getHostName();
            for (int i=0; i<_remoteServers.length; i++)
            {
                if (hostName.equals(_remoteServers[i])||hostAddr.equals(_remoteServers[i]))
                {
                    match=true;
                    break;
                }
            }
            if (!match)
            {
                log.warn("AJP13 Connection from un-approved host: "+inetAddress);
                return;
            }
        }

        // Handle the connection
        socket.setTcpNoDelay(true);
        socket.setSoTimeout(getMaxIdleTimeMs());
        AJP13Connection connection=createConnection(socket);
        try
        {
            connection.handle();
        }
        finally
        {
            connection.destroy();
        }
    }
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}
1086642
function (server_type, socket_url, connHandler, onDone) {

		// handles when connection with server is established
		var onConnect = function () {
			
			if (typeof connHandler === 'function')
				connHandler('connect');
			
			SR.Log('websocket server connected: ' + socket_url);
			if (typeof onDone === 'function')
				onDone();
		}
		
		// disconnect event
		var onDisconnect = function (obj) {
			if (typeof connHandler === 'function')
				connHandler('disconnect');
			
			SR.Warn('disconnected... obj: ');
			SR.Warn(obj);
			
			// attempt to re-connect
			if (typeof conn_options === 'object') {
				removeEntry(currentEntry);
				currentEntry = undefined;
				SR.Warn('re-connecting websocket with options');
				SR.Warn(conn_options);
				SR.setSocketServer(conn_options);
			}
		}
		
		// configure priority of protocol used
		//io.configure(function () { 
			//io.set("transports", ["xhr-polling", "flashsocket", "json-polling"]); 
		//});
				
		// connect to server
		SR.Log('connecting to server: ' + socket_url);
            
		if (server_type === 'socketio') {
            
			socket = io.connect(
				socket_url
				/*
				{	
					'reconnection delay': 10000,
					'reconnection limit': 4,
     	 			'max reconnection attempts': 4
				}
				*/
			);
			
			var generateHandler = function (name) {
				return function () {
					if (typeof connHandler === 'function')
						connHandler(name);
				}
			}
			
			// Return socket connection status and response
			for (var i=0; i < socketEvents.length; i++) {
				var event_name = socketEvents[i];
				socket.on(event_name, generateHandler(event_name));
			}
			
            // connection success
            socket.on('connect', onConnect);
			socket.on('disconnect', onDisconnect);
			
			// move this outside of 'connect' event handling (to avoid duplicates)
			socket.on('SRR', function (data) {
				SR.Log('SRR received, type: ' + data[HEADER_UPDATE]);
				onResponse(data[HEADER_UPDATE], data[HEADER_PARA]);
			});
            
            // attach customized send function
            socket.sendJSON = function (obj) {
                socket.emit('SR', obj);
            }
		}
		else if (server_type === 'sockjs') {
			socket = {};
			var url = socket_url + '/sockjs';
			SR.Log('sockjs URL to connect: ' + url);

            // Create a connection to server
            var sock = new SockJS(url);
    
            // Open the connection
			sock.onopen = function () {
				socket.opened = true;
				// send cookie explicitly
				SR.Warn('sockjs sending cookie:');
				SR.Warn(document.cookie);
				sock.send(document.cookie);
				onConnect();
			}
			
            // On connection close
            sock.onclose = onDisconnect;

            // On receive message from server
            sock.onmessage = function (e) {
                // Get the content
                var obj = JSON.parse(e.data);
				onResponse(obj[HEADER_UPDATE], obj[HEADER_PARA]);
            }
            
            // attach customized send function
			
			socket.sendJSON = function (obj) {
								sock.send(JSON.stringify(obj));
            				};
		}
		else  {
			SR.Error('unrecongizable server_type: ' + server_type + ' please check if socket.io or sockjs is used');	
		}
	}
499919
function onConnect(err) {
    if (err) {
      DEBUG("connect error", err)
      return cb(err)
    }

    DEBUG("connected")

    channel.sendMessage({
      type: "request",
      name: "connect",
      to:   "server",
      id:   "0",
      body: {
        key: config.key
      }
    })
  }
691478
function() {
    const err = Errors.createError(
      'socket timeout',
      true,
      info,
      '08S01',
      Errors.ER_SOCKET_TIMEOUT
    );
    const packetMsgs = info.getLastPackets();
    if (packetMsgs !== '') {
      err.message = err.message + '\nlast received packets:\n' + packetMsgs;
    }
    _fatalError(err, true);
  }
662368
function connectServer(options, cb) {
    var socket = new net.Socket();
    var start = process.hrtime();

    socket.connect(options.port, options.address, function() {
        var time_arr = process.hrtime(start);
        var time = (time_arr[0] * 1e9 + time_arr[1]) / 1e6;
        results.push({
            seq:  count,
            time: time
        });
        try { socket.destroy(); } catch(e) {}
        count++;
        checkConnection(options, cb);
    });

    socket.on('error', function(e) {
        results.push({
            seq:  count,
            time: undefined,
            err:  e
        });
        try { socket.destroy(); } catch(e) {}
        count++;
        checkConnection(options, cb);
    });

    socket.setTimeout(options.timeout, function() {
        results.push({
            seq:  count,
            time: undefined,
            err:  Error('Request timeout')
        });
        try { socket.destroy(); } catch(e) {}
        count++;
        checkConnection(options, cb);
    });
}
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);
}
163247
def run(self):
        

        self.ws = self.connect()
        while True:
            try:
                data = json.loads(self.ws.recv())
                self.handle(data)
            except json.decoder.JSONDecodeError as e:
                logger.fatal("No data on socket...")