Connection handler thread. Takes care of communication with the client 
        and running the proper task or applying a signal.
333958
def _handler(self, conn):
        
        incoming = self.recv(conn)
        self.log(DEBUG, incoming)
        try:
            # E.g. ['twister', [7, 'invert'], {'guess_type': True}]
            task, args, kw = self.codec.decode(incoming)
            
            # OK, so we've received the information. Now to use it.
            self.log(INFO, 'Fulfilling task %r' % task)
            self.started_task()
            
            pass_backend = False
            obj = self.tasks[task]
            if _is_iter(obj):
                # (callable, bool)
                obj, pass_backend = obj
            if pass_backend:
                # Have to do this, since args is a list
                args = [self] + args
            
            # Get and package the result
            res = ['success', obj(*args, **kw)]
        except Exception as e:
            self.log(ERROR, 'Error while fullfilling task %r: %r' % (task, e))
            res = ['error', e.__class__.__name__, e.args]
            if self.tracebacks:
                show_err()
        else:
            self.log(INFO, 'Finished fulfilling task %r' % task)
        finally:
            self.send(conn, self.codec.encode(res))
            self.finished_task()
            conn.close()
140402
def _connect(self):
        
        if not self.connected.is_set():
            try:
                self.lock.acquire()
                # Another thread may have connected while we were
                # waiting to acquire the lock
                if not self.connected.is_set():
                    self._do_connect()
                    if self.keepalive:
                        self._transport.set_keepalive(self.keepalive)
                    self.connected.set()
            except GerritError:
                raise
            finally:
                self.lock.release()
485493
public void connectClient(Connection connection) {
    threadContext.checkThread();

    // Note we do not use method references here because the "state" variable changes over time.
    // We have to use lambdas to ensure the request handler points to the current state.
    connection.handler(RegisterRequest.class, (Function<RegisterRequest, CompletableFuture<RegisterResponse>>) request -> state.register(request));
    connection.handler(ConnectRequest.class, (Function<ConnectRequest, CompletableFuture<ConnectResponse>>) request -> state.connect(request, connection));
    connection.handler(KeepAliveRequest.class, (Function<KeepAliveRequest, CompletableFuture<KeepAliveResponse>>) request -> state.keepAlive(request));
    connection.handler(UnregisterRequest.class, (Function<UnregisterRequest, CompletableFuture<UnregisterResponse>>) request -> state.unregister(request));
    connection.handler(ResetRequest.class, (Consumer<ResetRequest>) request -> state.reset(request));
    connection.handler(CommandRequest.class, (Function<CommandRequest, CompletableFuture<CommandResponse>>) request -> state.command(request));
    connection.handler(QueryRequest.class, (Function<QueryRequest, CompletableFuture<QueryResponse>>) request -> state.query(request));

    connection.onClose(stateMachine.executor().context().sessions()::unregisterConnection);
  }
773585
def serve(application, host='127.0.0.1', port=8080, threads=4, **kw):
	
	
	# Bind and start the server; this is a blocking process.
	serve_(application, host=host, port=int(port), threads=int(threads), **kw)
624740
private void doConnect(){
        task = new SocketDeamonTask();
        connectThread = new Thread(task);
        connectThread.setDaemon(true);
        connectThread.start();
    }
217610
async def _handle(self, reader, writer):
        
        peer = writer.get_extra_info('peername')
        self._logger.debug('New connection from {}'.format(peer))
        try:
            # Loop handling requests
            while True:
                # Read the request
                req = Request()
                await req._read(reader)

                # Find and execute handler
                res = None
                for path_regex, handler in self._handlers.get(req.method, []):
                    match = path_regex.fullmatch(req.path)
                    if match:
                        req.match = match
                        try:
                            if inspect.iscoroutinefunction(handler):
                                res = await handler(self.env, req)
                            else:
                                res = handler(self.env, req)
                            if not isinstance(res, Response):
                                res = Response(data=res)
                        except:
                            # Error - log it and return 500
                            self._logger.error(traceback.format_exc())
                            res = Response(code=500, reason='Internal Server Error')
                        break

                # No handler - send 404
                if res == None:
                    res = Response(code=404, reason='Not Found')

                # Respond
                await res._write(writer)
                self._logger.info('{}: {} -> {}'.format(peer, req.path,  res.code))
        except EOFError:
            self._logger.debug('Connection closed from {}'.format(peer))
        except Exception as e:
            self._logger.error('Connection error ({}) from {}'.format(e, peer))
            writer.close()
933232
public static void detectDeadConnections() {
        if (CONNECTION_DETECTOR_RUNNING) {
            return;
        }
        final Logger log = LoggerFactory.getLogger(ConnectionManager.class);
        Thread deadConnThread = new Thread(new Runnable() {
            public void run() {
                CONNECTION_DETECTOR_RUNNING = true;
                try {
                    log.debug("Starting dead connection detection thread");
                    while (detectDeadConnection) {
                        log.debug("Checking if there are any dead connections");
                        long now = DateTime.now().getMillis();
                        for (DataSiftConnection data : connections) {
                            if (data.lastSeen() != null) {
                                if (now - data.lastSeen().getMillis() >=
                                        TimeUnit.SECONDS.toMillis(CONNECTION_TIMEOUT_LIMIT)) {
                                    log.info("Dead connection found, triggering re-connection");
                                    data.closeAndReconnect();
                                }
                            }
                        }
                        log.debug(String.format("Checked %s connections", connections.size()));
                        try {
                            Thread.sleep(TimeUnit.SECONDS.toMillis(CONNECTION_TIMEOUT));
                        } catch (InterruptedException e) {
                            LoggerFactory.getLogger(getClass()).info("Interrupted while waiting to check conn");
                        }
                    }
                } finally {
                    CONNECTION_DETECTOR_RUNNING = false;
                }
            }
        }, "dead-connections-monitor");
        deadConnThread.setDaemon(true);
        deadConnThread.start();
    }
920525
public static void registerBlockedThreadHandler(BlockedThreadHandler handler, Thread thread) {
		synchronized (blockedHandlers) {
			blockedHandlers.put(thread, handler);
		}
	}
238229
def start(self):
        '''
        
        '''
        self._handler = _create_handler_class(self._rules, self._always_rules)
        self._server = HTTPServer(('', self._port), self._handler)
        self._thread = Thread(target=self._server.serve_forever, daemon=True)
        self._thread.start()
        self.running = True
        return self
1183712
def async_session_handler(self, signal: str) -> None:
        
        if signal == 'data':
            self.async_event_handler(self.websocket.data)
        elif signal == 'state':
            if self.async_connection_status_callback:
                self.async_connection_status_callback(
                    self.websocket.state == 'running')
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
1295440
private void startHandleModifyThread(final WatchEvent<?> event, final Path currentPath) {
		ThreadUtil.execute(new Runnable(){
			@Override
			public void run() {
				ThreadUtil.sleep(delay);
				eventSet.remove(Paths.get(currentPath.toString(), event.context().toString()));
				watcher.onModify(event, currentPath);
			}
		});
	}
203445
private function processConnectionPool(): void
    {
        $readableConnections = $this->connectionPool->getReadableConnections(5);

        foreach ($readableConnections as $id => $connection) {
            if (!isset($this->connectionHandlers[$id])) {
                $this->connectionHandlers[$id] = $this->connectionHandlerFactory->createConnectionHandler($this->kernel, $connection);
            }

            try {
                $statusCodes = $this->connectionHandlers[$id]->ready();
                $this->considerStatusCodes($statusCodes);
            } catch (UserlandDaemonException $exception) {
                $this->daemonOptions->getOption(DaemonOptions::LOGGER)->error($exception->getMessage());
            }

            if ($this->connectionHandlers[$id]->isClosed()) {
                unset($this->connectionHandlers[$id]);
            }
        }
    }
727575
def process_request_thread(self, request, client_address):
        

        try:
            self.finish_request(request, client_address)
            self.shutdown_request(request)
        except Exception as e:
            self.logger.error(e)
            self.handle_error(request, client_address)
            self.shutdown_request(request)
1246732
def listen(self):
        

        # Make sure we're in server mode
        if self.mode and self.mode != 'server':
            raise ValueError("%s is not in server mode" %
                             self.__class__.__name__)
        self.mode = 'server'

        # Obtain a listening socket
        serv = _create_server(self.host, self.port)

        # If we have too many errors, we want to bail out
        err_thresh = 0
        while True:
            # Accept a connection
            try:
                sock, addr = serv.accept()
            except Exception as exc:
                err_thresh += 1
                if err_thresh >= self.max_err_thresh:
                    LOG.exception("Too many errors accepting "
                                  "connections: %s" % str(exc))
                    break
                continue  # Pragma: nocover

            # Decrement error count on successful connections
            err_thresh = max(err_thresh - 1, 0)

            # Log the connection attempt
            LOG.info("Accepted connection from %s port %s" %
                     (addr[0], addr[1]))

            # And handle the connection
            eventlet.spawn_n(self.serve, self.connection_class(sock), addr)

        # Close the listening socket
        with utils.ignore_except():
            serv.close()
237258
private int processConnections(Iterator<H> handlers) {
        int nHandles = 0;
        
        // Loop on each connection request
        while (handlers.hasNext()) {
            H handle = handlers.next();
            handlers.remove();

            ConnectionRequest connectionRequest = getConnectionRequest(handle);
            
            if ( connectionRequest == null) {
                continue;
            }
            
            boolean success = false;
            try {
                if (finishConnect(handle)) {
                    T session = newSession(processor, handle);
                    initSession(session, connectionRequest, connectionRequest.getSessionInitializer());
                    // Forward the remaining process to the IoProcessor.
                    session.getProcessor().add(session);
                    nHandles ++;
                }
                success = true;
            } catch (Throwable e) {
                connectionRequest.setException(e);
            } finally {
                if (!success) {
                    // The connection failed, we have to cancel it.
                    cancelQueue.offer(connectionRequest);
                }
            }
        }
        return nHandles;
    }
447349
def start(self):
        
        self.thread_handler.run(target=self.start_blocking)
        self.thread_handler.start_run_loop()