Handles a connection to a server.
436933
private void handleConnection(Address address, Connection connection, Throwable error, CompletableFuture<Connection> future) {
    if (open) {
      if (error == null) {
        setupConnection(address, connection, future);
      } else {
        LOGGER.debug("{} - Failed to connect! Reason: {}", id, error);
        connect(future);
      }
    }
  }
1015489
def _handle_incoming_data(self, conn):
        
        connection = [c for c in self.connections if c.conn == conn][0]
        data = conn.recv(1024)
        if data:
            connection.feed(data)
        else:
            self.connections.remove(connection)
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')
418597
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 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, e:
            errnum = e.args[0]
            # sadly SSL sockets return a different (longer) time out string
            if errnum == 'timed out' or errnum == 'The read operation timed out':
                # 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 http://www.cherrypy.org/ticket/853
                if (not request_seen) or (req and req.started_request):
                    # Don't bother writing the 408 if the response
                    # has already started being written.
                    if req and not req.sent_headers:
                        try:
                            req.simple_response("408 Request Timeout")
                        except FatalSSLAlert:
                            # Close the connection.
                            return
            elif errnum not in socket_errors_to_ignore:
                if req and not req.sent_headers:
                    try:
                        req.simple_response("500 Internal Server Error",
                                            format_exc())
                    except FatalSSLAlert:
                        # Close the connection.
                        return
            return
        except (KeyboardInterrupt, SystemExit):
            raise
        except FatalSSLAlert:
            # Close the connection.
            return
        except NoSSLError:
            if req and not req.sent_headers:
                # Unwrap our wfile
                self.wfile = CP_fileobject(self.socket._sock, "wb", self.wbufsize)
                req.simple_response("400 Bad Request",
                    "The client sent a plain HTTP request, but "
                    "this server only speaks HTTPS on this port.")
                self.linger = True
        except Exception:
            if req and not req.sent_headers:
                try:
                    req.simple_response("500 Internal Server Error", format_exc())
                except FatalSSLAlert:
                    # Close the connection.
                    return
1196864
def handle(self, url, method):
        
        if not self.serve:
            return HTTPError(503, "Server stopped")

        handler, args = self.match_url(url, method)
        if not handler:
            return HTTPError(404, "Not found:" + url)

        try:
            return handler(**args)
        except HTTPResponse, e:
            return e
        except Exception, e:
            if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\
            or not self.catchall:
                raise
            return HTTPError(500, 'Unhandled exception', e, format_exc(10))
697967
def serve(application, host='127.0.0.1', port=8080):
	
	
	# Instantiate the server with a bound port and with our application.
	server(listen(host, int(port)), application)
504307
def serve(self, host='', port=8000, no_documentation=False, display_intro=True):
        """"""
        if no_documentation:
            api = self.server(None)
        else:
            api = self.server()

        if display_intro:
            print(INTRO)

        httpd = make_server(host, port, api)
        print("Serving on {0}:{1}...".format(host, port))
        httpd.serve_forever()
792659
def handle_error(_, client_addr):
        """"""
        exc_type, exc_value, _ = sys.exc_info()
        if exc_type is socket.error and exc_value[0] == 32:
            pass
        elif exc_type is cPickle.UnpicklingError:
            sys.stderr.write('Invalid connection from {0}\n'
                             .format(client_addr[0]))
        else:
            raise
714056
function handleConnection(socket) { // server 'connect'
		socket.setEncoding('utf-8')
		socket.on('data', requestResponder)

		function requestResponder(data) {
			socket.end(String(process.pid))
			self.emit('data', data)
		}
	}
450286
def handle(self, sock, read_data, path, headers):
        ""
        if "://" not in self.redirect_to:
            destination = "http%s://%s" % (
                "s" if headers.get('X-Forwarded-Protocol', headers.get('X-Forwarded-Proto', "")).lower() in ("https", "ssl") else "",
                self.redirect_to
            )
        else:
            destination = self.redirect_to
        try:
            sock.sendall("HTTP/1.0 302 Found\r\nLocation: %s/%s\r\n\r\n" % (
                destination.rstrip("/"),
                path.lstrip("/"),
            ))
        except socket.error, e:
            if e.errno != errno.EPIPE:
                raise
327797
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException
    {
        URI uri = request.getURI();

        // Is this a CONNECT request?
        if (HttpRequest.__CONNECT.equalsIgnoreCase(request.getMethod()))
        {
            response.setField(HttpFields.__Connection, "close"); // TODO Needed for IE????
            handleConnect(pathInContext, pathParams, request, response);
            return;
        }

        try
        {
            // Do we proxy this?
            URL url = isProxied(uri);
            if (url == null)
            {
                if (isForbidden(uri))
                    sendForbid(request, response, uri);
                return;
            }

            if (log.isDebugEnabled())
                log.debug("PROXY URL=" + url);

            URLConnection connection = url.openConnection();
            connection.setAllowUserInteraction(false);

            // Set method
            HttpURLConnection http = null;
            if (connection instanceof HttpURLConnection)
            {
                http = (HttpURLConnection) connection;
                http.setRequestMethod(request.getMethod());
                http.setInstanceFollowRedirects(false);
            }

            // check connection header
            String connectionHdr = request.getField(HttpFields.__Connection);
            if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close)))
                connectionHdr = null;

            // copy headers
            boolean xForwardedFor = false;
            boolean hasContent = false;
            Enumeration enm = request.getFieldNames();
            while (enm.hasMoreElements())
            {
                // TODO could be better than this!
                String hdr = (String) enm.nextElement();

                if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr))
                    continue;
                if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0)
                    continue;

                if (HttpFields.__ContentType.equals(hdr))
                    hasContent = true;

                Enumeration vals = request.getFieldValues(hdr);
                while (vals.hasMoreElements())
                {
                    String val = (String) vals.nextElement();
                    if (val != null)
                    {
                        connection.addRequestProperty(hdr, val);
                        xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr);
                    }
                }
            }

            // Proxy headers
            if (!_anonymous)
                connection.setRequestProperty("Via", "1.1 (jetty)");
            if (!xForwardedFor)
                connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr());

            // a little bit of cache control
            String cache_control = request.getField(HttpFields.__CacheControl);
            if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
                connection.setUseCaches(false);

            // customize Connection
            customizeConnection(pathInContext, pathParams, request, connection);

            try
            {
                connection.setDoInput(true);

                // do input thang!
                InputStream in = request.getInputStream();
                if (hasContent)
                {
                    connection.setDoOutput(true);
                    IO.copy(in, connection.getOutputStream());
                }

                // Connect
                connection.connect();
            }
            catch (Exception e)
            {
                LogSupport.ignore(log, e);
            }

            InputStream proxy_in = null;

            // handler status codes etc.
            int code = HttpResponse.__500_Internal_Server_Error;
            if (http != null)
            {
                proxy_in = http.getErrorStream();

                code = http.getResponseCode();
                response.setStatus(code);
                response.setReason(http.getResponseMessage());
            }

            if (proxy_in == null)
            {
                try
                {
                    proxy_in = connection.getInputStream();
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                    proxy_in = http.getErrorStream();
                }
            }

            // clear response defaults.
            response.removeField(HttpFields.__Date);
            response.removeField(HttpFields.__Server);

            // set response headers
            int h = 0;
            String hdr = connection.getHeaderFieldKey(h);
            String val = connection.getHeaderField(h);
            while (hdr != null || val != null)
            {
                if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr)))
                    response.addField(hdr, val);
                h++;
                hdr = connection.getHeaderFieldKey(h);
                val = connection.getHeaderField(h);
            }
            if (!_anonymous)
                response.setField("Via", "1.1 (jetty)");

            // Handled
            request.setHandled(true);
            if (proxy_in != null)
                IO.copy(proxy_in, response.getOutputStream());

        }
        catch (Exception e)
        {
            log.warn(e.toString());
            LogSupport.ignore(log, e);
            if (!response.isCommitted())
                response.sendError(HttpResponse.__400_Bad_Request);
        }
    }
218210
def handle(self):
        ''''''
        try:
            yield self
        except:
            # Requeue the message and raise the original exception
            typ, value, trace = sys.exc_info()
            if not self.processed:
                try:
                    self.req(self.delay())
                except socket.error:
                    self.connection.close()
            raise typ, value, trace
        else:
            if not self.processed:
                try:
                    self.fin()
                except socket.error:
                    self.connection.close()
11481
def handle(self):
        """"""
        self.close_connection = 1

        self.handle_one_request()
        while not self.close_connection:
            self.handle_one_request()
738254
protected void handle(HttpConnection httpConnection) throws IOException {
		try {
			getServerThread().handleIncomingHttp(httpConnection);
			httpConnection.waitForResponse();
		}
		catch (ConnectException ex) {
			httpConnection.respond(HttpStatus.GONE);
		}
	}
507053
def handle(self):
        
        logger = StreamHandler.logger
        logger.debug("handling requests with message handler %s " % StreamHandler.message_handler.__class__.__name__)

        message_handler = StreamHandler.message_handler

        try:
            while True:
                logger.debug('waiting for more data')
                if not message_handler.handle(self.request, StreamHandler.BUFFER_SIZE):
                    break

            logger.warning("connection closed from %s" % (self.client_address[0]))
            self.request.close()
        except:
            logger.exception("connection closed from %s" % (self.client_address[0]))
        finally:
            self.request.close()
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
      }
    })
  }
383098
public void connectServer(Connection connection) {
    threadContext.checkThread();

    // Handlers for all request types are registered since requests can be proxied between servers.
    // 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(ConfigureRequest.class, (Function<ConfigureRequest, CompletableFuture<ConfigureResponse>>) request -> state.configure(request));
    connection.handler(InstallRequest.class, (Function<InstallRequest, CompletableFuture<InstallResponse>>) request -> state.install(request));
    connection.handler(JoinRequest.class, (Function<JoinRequest, CompletableFuture<JoinResponse>>) request -> state.join(request));
    connection.handler(ReconfigureRequest.class, (Function<ReconfigureRequest, CompletableFuture<ReconfigureResponse>>) request -> state.reconfigure(request));
    connection.handler(LeaveRequest.class, (Function<LeaveRequest, CompletableFuture<LeaveResponse>>) request -> state.leave(request));
    connection.handler(AppendRequest.class, (Function<AppendRequest, CompletableFuture<AppendResponse>>) request -> state.append(request));
    connection.handler(PollRequest.class, (Function<PollRequest, CompletableFuture<PollResponse>>) request -> state.poll(request));
    connection.handler(VoteRequest.class, (Function<VoteRequest, CompletableFuture<VoteResponse>>) request -> state.vote(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);
  }