Handles a connection from a client.
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);
  }
720356
private void handleRequest(ByteBuf request, ChannelHandlerContext context) {
    NettyConnection connection = getConnection(context.channel());
    if (connection != null) {
      connection.handleRequest(request);
    }
  }
1369153
private void doConnect() throws SessionTimeOutException{
        long to = getConnectTimeOut();

        if(clientSocket.isConnected()){
            ErrorCode ec = sendConnectProtocol(to);
            // CONNECTION_LOSS means client data is inconsistence with server. now we check the last dxid of client.
            // if dxid of the client is bigger than server actual dxid, return CONNECTION_LOSS.
            if(ErrorCode.SESSION_EXPIRED.equals(ec) || ErrorCode.CONNECTION_LOSS.equals(equals(ec))){
                LOGGER.info("Session Expired, cleanup the client session.");
                cleanupSession();
            }
        }
    }
545838
void handleCommunicationIssue(Exception io) {
        // If we are connecting or disconnecting, note exception and leave
        statusLock.lock();
        try {
            if (this.connecting || this.disconnecting || this.status == Status.CLOSED || this.isDraining()) {
                this.exceptionDuringConnectChange = io;
                return;
            }
        } finally {
            statusLock.unlock();
        }

        processException(io);

        // Spawn a thread so we don't have timing issues with
        // waiting on read/write threads
        executor.submit(() -> {
            try {
                this.closeSocket(true);
            } catch (InterruptedException e) {
                processException(e);
            }
        });
    }
234965
def on_connect(self, connection):
        
        self._sock = connection._sock
        self._buffer = SocketBuffer(self._sock, self.socket_read_size)        
        if connection.decode_responses:
            self.encoding = connection.encoding
601739
private void handleKey(Selector selector, SelectionKey key) throws IOException {
        if (key.isValid() && key.isAcceptable()) {
            // Accept a new connection, give it a stream connection as an attachment
            SocketChannel newChannel = sc.accept();
            newChannel.configureBlocking(false);
            SelectionKey newKey = newChannel.register(selector, SelectionKey.OP_READ);
            try {
                ConnectionHandler handler = new ConnectionHandler(connectionFactory, newKey);
                newKey.attach(handler);
                handler.connection.connectionOpened();
            } catch (IOException e) {
                // This can happen if ConnectionHandler's call to get a new handler returned null
                log.error("Error handling new connection", Throwables.getRootCause(e).getMessage());
                newKey.channel().close();
            }
        } else { // Got a closing channel or a channel to a client connection
            ConnectionHandler.handleKey(key);
        }
    }
550245
def handle_request(self):
        
        try:
            (request, client_address) = self.get_request()

        except socket.error as e:
            # Error handling goes here.
            self.logger.error("error opening the connection: %s" % (
                str(e)))
            for exctn in sys.exc_info():
                print(exctn)
            return

        try:
            self.RequestHandlerClass(request, client_address, self)
        except Exception as e:
            # Error handling goes here.
            self.logger.error('error handling the request: %s' % (
                str(e)))
            for exctn in sys.exc_info():
                print(exctn)
            return
1135749
def _handle_stream(self, stream, address):
        """"""
        try:
            assert get_thread_ident() == self.ioloop_thread_id
            stream.set_close_callback(partial(self._stream_closed_callback,
                                              stream))
            # Our message packets are small, don't delay sending them.
            stream.set_nodelay(True)
            stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE

            # Abuse IOStream object slightly by adding 'address' and 'closing'
            # attributes. Use nasty prefix to prevent naming collisions.
            stream.KATCPServer_address = address
            # Flag to indicate that no more write should be accepted so that
            # we can flush the write buffer when closing a connection
            stream.KATCPServer_closing = False

            client_conn = self.client_connection_factory(self, stream)
            self._connections[stream] = client_conn
            try:
                yield gen.maybe_future(self._device.on_client_connect(client_conn))
            except Exception:
                # If on_client_connect fails there is no reason to continue
                # trying to handle this connection. Try and send exception info
                # to the client and disconnect
                e_type, e_value, trace = sys.exc_info()
                reason = "\n".join(traceback.format_exception(
                    e_type, e_value, trace, self._tb_limit))
                log_msg = 'Device error initialising connection {0}'.format(reason)
                self._logger.error(log_msg)
                stream.write(str(Message.inform('log', log_msg)))
                stream.close(exc_info=True)
            else:
                self._line_read_loop(stream, client_conn)
        except Exception:
            self._logger.error('Unhandled exception trying '
                               'to handle new connection', exc_info=True)
973854
protected void handleClient(final Socket client) throws IOException {
		final ClientHandler handler = new ClientHandler(client);
		this.executorService.execute(handler);
	}
1344224
def handle_request(self):
        
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                # we only serve once, and we want to free up the port
                # for future serves.
                self.socket.close()
                self.process_request(request, client_address)
            except SocketConnected as err:
                self._serve_process(err.slaveFd, err.serverPid)
                return
            except Exception as err:
                self.handle_error(request, client_address)
                self.close_request()
297011
def _handle_connect(self, sid, namespace):
        """"""
        namespace = namespace or '/'
        self.manager.connect(sid, namespace)
        if self.always_connect:
            self._send_packet(sid, packet.Packet(packet.CONNECT,
                                                 namespace=namespace))
        fail_reason = None
        try:
            success = self._trigger_event('connect', namespace, sid,
                                          self.environ[sid])
        except exceptions.ConnectionRefusedError as exc:
            fail_reason = exc.error_args
            success = False

        if success is False:
            if self.always_connect:
                self.manager.pre_disconnect(sid, namespace)
                self._send_packet(sid, packet.Packet(
                    packet.DISCONNECT, data=fail_reason, namespace=namespace))
            self.manager.disconnect(sid, namespace)
            if not self.always_connect:
                self._send_packet(sid, packet.Packet(
                    packet.ERROR, data=fail_reason, namespace=namespace))
            if sid in self.environ:  # pragma: no cover
                del self.environ[sid]
            return False
        elif not self.always_connect:
            self._send_packet(sid, packet.Packet(packet.CONNECT,
                                                 namespace=namespace))
348916
async def handle_client_hello(self, client_addr, _: ClientHello):
        
        self._logger.info("New client connected %s", client_addr)
        self._registered_clients.add(client_addr)
        await self.send_container_update_to_client([client_addr])
237304
def handle_request(self):
        """"""
        try:
            request, client_address = self.get_request()
        except socket.error:
            return

        if self.verify_request(request, client_address):
            self.workerpool.run(self.process_request_thread,
                                **{'request': request,
                                   'client_address': client_address})
1249985
public void clientDisconnect()
  {
    try {
      OutHttpApp responseStream = _responseStream;
      
      if (responseStream != null) {
        responseStream.close();
      }
    } catch (Exception e) {
      log.log(Level.FINER, e.toString(), e);
    }
    
    ConnectionTcp conn = connTcp();

    if (conn != null) {
      conn.clientDisconnect();
    }

    killKeepalive("client disconnect");
  }
452146
public void handle(ServerHttpRequest request, ServerHttpResponse response)
			throws IOException {
		handle(new HttpConnection(request, response));
	}
968009
def _handle_connect(self, environ, start_response, transport, b64=False):
        """"""
        if self.start_service_task:
            # start the service task to monitor connected clients
            self.start_service_task = False
            self.start_background_task(self._service_task)

        sid = self._generate_id()
        s = socket.Socket(self, sid)
        self.sockets[sid] = s

        pkt = packet.Packet(
            packet.OPEN, {'sid': sid,
                          'upgrades': self._upgrades(sid, transport),
                          'pingTimeout': int(self.ping_timeout * 1000),
                          'pingInterval': int(self.ping_interval * 1000)})
        s.send(pkt)

        ret = self._trigger_event('connect', sid, environ, run_async=False)
        if ret is False:
            del self.sockets[sid]
            self.logger.warning('Application rejected connection')
            return self._unauthorized()

        if transport == 'websocket':
            ret = s.handle_get_request(environ, start_response)
            if s.closed:
                # websocket connection ended, so we are done
                del self.sockets[sid]
            return ret
        else:
            s.connected = True
            headers = None
            if self.cookie:
                headers = [('Set-Cookie', self.cookie + '=' + sid)]
            try:
                return self._ok(s.poll(), headers=headers, b64=b64)
            except exceptions.QueueEmpty:
                return self._bad_request()
752692
async def _manage_connection(self):
        """"""

        try:
            while True:
                message = await self._con.recv()

                try:
                    unpacked = unpack(message)
                except Exception:  # pylint:disable=broad-except;This is a background worker
                    self._logger.exception("Corrupt message received")
                    continue

                if not VALID_SERVER_MESSAGE.matches(unpacked):
                    self._logger.warning("Dropping invalid message from server: %s", unpacked)
                    continue

                # Don't block until all callbacks have finished since once of
                # those callbacks may call self.send_command, which would deadlock
                # since it couldn't get the response until it had already finished.
                if not await self._manager.process_message(unpacked, wait=False):
                    self._logger.warning("No handler found for received message, message=%s", unpacked)
        except asyncio.CancelledError:
            self._logger.info("Closing connection to server due to stop()")
        finally:
            await self._manager.process_message(dict(type='event', name=self.DISCONNECT_EVENT, payload=None))
            await self._con.close()