Handle a client connection request.
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()
1116876
async def send_request(self, params, timeout,
                           type='json_query', command=False):
        """"""
        try:
            with async_timeout.timeout(timeout):
                url = '{url}{type}'.format(
                    url=self._http_url,
                    type=type)
                async with self.websession.get(
                    url=url, params=params,
                        headers=self._headers) as response:
                    if response.status != HTTP_OK:
                        _LOGGER.warning(
                            "Error message %d from Epson.", response.status)
                        return False
                    if command == TURN_ON and self._powering_on:
                        self._powering_on = False
                    if type == 'json_query':
                        return await response.json()
                    return response
        except (aiohttp.ClientError, aiohttp.ClientConnectionError):
            _LOGGER.error("Error request")
            return False
736214
def _handle_client(self):
        
        while True:
            try:
                # Wait for connection.
                logger.info('Waiting for connection in pipe instance.')
                yield From(self._connect_client())
                logger.info('Connected in pipe instance')

                conn = Win32PipeConnection(self)
                self.pipe_connection_cb(conn)

                yield From(conn.done_f)
                logger.info('Pipe instance done.')

            finally:
                # Disconnect and reconnect.
                logger.info('Disconnecting pipe instance.')
                windll.kernel32.DisconnectNamedPipe(self.pipe_handle)
1220380
public void requestDone() {
        currentRequest = null;

        if (anyAreSet(state, CLOSE_REQ)) {
            safeClose(connection);
        } else if (anyAreSet(state, UPGRADE_REQUESTED)) {
            safeClose(connection); //we don't support upgrade, just close the connection to be safe
            return;
        }

        AjpClientExchange next = pendingQueue.poll();

        if (next != null) {
            initiateRequest(next);
        }
    }
722404
def _serve_clients(self):
        '''
        
        '''
        self.__up = True
        while self.__up:
            log.debug('Waiting for a client to connect')
            try:
                conn, addr = self.skt.accept()
                log.debug('Received connection from %s:%d', addr[0], addr[1])
            except socket.error as error:
                if not self.__up:
                    return
                msg = 'Received listener socket error: {}'.format(error)
                log.error(msg, exc_info=True)
                raise ListenerException(msg)
            client_thread = threading.Thread(target=self._client_connection, args=(conn, addr,))
            client_thread.start()
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
1114573
def handleStatus(self, version, code, message):
        ""
        proxy.ProxyClient.handleStatus(self, version, code, message)
        # client.Response is currently just a container for needed data
        self._response = client.Response(version, code, message, {}, None)
1260557
def _make_request(self, conn, method, url, timeout=_Default,
                      **httplib_request_kw):
        
        self.num_requests += 1

        if timeout is _Default:
            timeout = self.timeout

        conn.request(method, url, **httplib_request_kw)
        conn.sock.settimeout(timeout)
        httplib_response = conn.getresponse()

        log.debug("\"%s %s %s\" %s %s" %
                  (method, url,
                   conn._http_vsn_str, # pylint: disable-msg=W0212
                   httplib_response.status, httplib_response.length))

        return httplib_response
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])
30779
def handle(self, sock, read_data, path, headers):
        ""
        for i in range(self.attempts):
            try:
                server_sock = eventlet.connect(
                    tuple(random.choice(self.backends)),
                )
            except socket.error:
                eventlet.sleep(self.delay)
                continue
            # Function to help track data usage
            def send_onwards(data):
                server_sock.sendall(data)
                return len(data)
            try:
                size = send_onwards(read_data)
                size += SocketMelder(sock, server_sock).run()
            except socket.error, e:
                if e.errno != errno.EPIPE:
                    raise
349672
def handle_request(request):
    
    connector = request['connector']
    hostname = connector['host']
    port = connector['port']
    virtual_host = connector['virtualHost']
    queue = connector['queue']
    user = connector['user']
    password = connector['password']
    # Establish connection with RabbitMQ server
    logging.info('Connect : [HOST=' + hostname + ', QUEUE=' + queue + ']')
    done = False
    attempts = 0
    while not done and attempts < 100:
        try:
            credentials = pika.PlainCredentials(user, password)
            con = pika.BlockingConnection(pika.ConnectionParameters(
                host=hostname,
                port=port,
                virtual_host=virtual_host,
                credentials=credentials
            ))
            channel = con.channel()
            channel.queue_declare(queue=queue, durable=True)
            req = request['request']
            logging.info('Run : [EXPERIMENT=' + req['experiment_id'] + ', RUN=' + req['run_id'] + ']')
            channel.basic_publish(
                exchange='',
                routing_key=queue,
                body=json.dumps(req),
                properties=pika.BasicProperties(
                    delivery_mode = 2, # make message persistent
                )
            )
            con.close()
            done = True
        except pika.exceptions.ConnectionClosed as ex:
            attempts += 1
            logging.exception(ex)
452146
public void handle(ServerHttpRequest request, ServerHttpResponse response)
			throws IOException {
		handle(new HttpConnection(request, response));
	}
343089
def communicate(self):
        """"""
        request_seen = False
        try:
            while True:
                # (re)set req to None so that if something goes wrong in
                # the RequestHandlerClass constructor, the error doesn't
                # get written to the previous request.
                req = None
                req = self.RequestHandlerClass(self.server, self)

                # This order of operations should guarantee correct pipelining.
                req.parse_request()
                if self.server.stats['Enabled']:
                    self.requests_seen += 1
                if not req.ready:
                    # Something went wrong in the parsing (and the server has
                    # probably already made a simple_response). Return and
                    # let the conn close.
                    return

                request_seen = True
                req.respond()
                if req.close_connection:
                    return
        except socket.error as ex:
            errnum = ex.args[0]
            # sadly SSL sockets return a different (longer) time out string
            timeout_errs = 'timed out', 'The read operation timed out'
            if errnum in timeout_errs:
                # Don't error if we're between requests; only error
                # if 1) no request has been started at all, or 2) we're
                # in the middle of a request.
                # See https://github.com/cherrypy/cherrypy/issues/853
                if (not request_seen) or (req and req.started_request):
                    self._conditional_error(req, '408 Request Timeout')
            elif errnum not in errors.socket_errors_to_ignore:
                self.server.error_log(
                    'socket.error %s' % repr(errnum),
                    level=logging.WARNING, traceback=True,
                )
                self._conditional_error(req, '500 Internal Server Error')
        except (KeyboardInterrupt, SystemExit):
            raise
        except errors.FatalSSLAlert:
            pass
        except errors.NoSSLError:
            self._handle_no_ssl(req)
        except Exception as ex:
            self.server.error_log(
                repr(ex), level=logging.ERROR, traceback=True,
            )
            self._conditional_error(req, '500 Internal Server Error')
243432
def __handler(self, connection, event):
        
        try:
            # Find local handler
            method = getattr(self, "on_{0}".format(event.type))
        except AttributeError:
            pass
        else:
            try:
                # Call it
                return method(connection, event)
            except Exception as ex:
                logging.exception("Error calling handler: %s", ex)
912085
async def start(self, connection: 'Connection') -> 'ClientResponse':
        """"""
        self._closed = False
        self._protocol = connection.protocol
        self._connection = connection

        with self._timer:
            while True:
                # read response
                try:
                    message, payload = await self._protocol.read()  # type: ignore  # noqa
                except http.HttpProcessingError as exc:
                    raise ClientResponseError(
                        self.request_info, self.history,
                        status=exc.code,
                        message=exc.message, headers=exc.headers) from exc

                if (message.code < 100 or
                        message.code > 199 or message.code == 101):
                    break

                if self._continue is not None:
                    set_result(self._continue, True)
                    self._continue = None

        # payload eof handler
        payload.on_eof(self._response_eof)

        # response status
        self.version = message.version
        self.status = message.code
        self.reason = message.reason

        # headers
        self._headers = message.headers  # type is CIMultiDictProxy
        self._raw_headers = message.raw_headers  # type is Tuple[bytes, bytes]

        # payload
        self.content = payload

        # cookies
        for hdr in self.headers.getall(hdrs.SET_COOKIE, ()):
            try:
                self.cookies.load(hdr)
            except CookieError as exc:
                client_logger.warning(
                    'Can not load response cookies: %s', exc)
        return self
907326
def handle_call(client, data)
      call_id, proc_uri, *args = data

      trigger(:call, client, call_id, proc_uri, args)
    end
689014
def _ensure_connection(self):
        """"""
        conn = self.connect()
        if conn.recycle and conn.recycle < time.time():
            logger.debug('Client session expired after %is. Recycling.', self._recycle)
            self.close()
            conn = self.connect()
        return conn