Expect a handshake from the remote host.

        :param headers:
            Headers to respond with
        :returns:
            A future that resolves (with a value of None) when the handshake
            is complete.
327064
def expect_handshake(self, headers):
        
        init_req = yield self.reader.get()
        if init_req.message_type != Types.INIT_REQ:
            raise errors.UnexpectedError(
                "You need to shake my hand first. Got %s" % repr(init_req)
            )
        self._extract_handshake_headers(init_req)
        self._handshake_performed = True

        self.writer.put(
            messages.InitResponseMessage(
                PROTOCOL_VERSION, headers, init_req.id),
        )

        # The receive loop is started only after the handshake has been
        # completed.
        self._loop()

        raise tornado.gen.Return(init_req)
460101
def _handle_headers(self):
        
        origin = self.request.headers.get('Origin')
        if not settings.DEBUG:
            if origin in settings.ALLOWED_ORIGINS or not origin:
                self.set_header('Access-Control-Allow-Origin', origin)
            else:
                log.debug("CORS ERROR: %s not allowed, allowed hosts: %s" % (origin,
                                                                             settings.ALLOWED_ORIGINS))
                raise HTTPError(403, "Origin not in ALLOWED_ORIGINS: %s" % origin)
        else:
            self.set_header('Access-Control-Allow-Origin', origin or '*')
        self.set_header('Access-Control-Allow-Credentials', "true")
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')
        self.set_header('Access-Control-Allow-Methods', 'OPTIONS')
        self.set_header('Content-Type', 'application/json')
377776
private void handshake() {
        JsonNode helloResponse = this.readNextResponse();

        if (!helloResponse.has("hello")) {
            throw new JsiiException("Expecting 'hello' message from jsii-runtime");
        }

        String runtimeVersion = helloResponse.get("hello").asText();
        assertVersionCompatible(JSII_RUNTIME_VERSION, runtimeVersion);
    }
429822
def get_header(self, name, default=None):
        
        return self._handler.headers.get(name, default)
553977
def success(headers = None, data = ''):
    
    passed_headers = {} if headers is None else headers
    if isinstance(data, dict): data = json.dumps(data)
    ret_headers = {'status' : 'ok'}
    ret_headers.update(passed_headers)
    return server_responce(ret_headers, data)
1275483
def begin(self):
        
        log.debug("handshake (version %s)" % PROTOCOL_VERSION)
        version = Version()
        version.services = 0    # can't send blocks
        log.debug("send Version")
        self.send_message(version)
948613
async def ws_handler(self, protocol, path):
        
        self.handshake_completed_event.set()
        await self.closed_event.wait()
461111
def start_handshake(self, timeout):
        
        if not self.__timer:
            self.__timer = threading.Timer(float(timeout), self.read_timer)
            self.__timer.start()
1180485
protected final void setHandshakeComplete() {
        synchronized (this) {
            handshakeComplete = true;
        }

        ProxyIoSession proxyIoSession = getProxyIoSession();
        proxyIoSession.getConnector()
                .fireConnected(proxyIoSession.getSession())
                .awaitUninterruptibly();

        LOGGER.debug("  handshake completed");

        // Connected OK
        try {
            proxyIoSession.getEventQueue().flushPendingSessionEvents();
            flushPendingWriteRequests();
        } catch (Exception ex) {
            LOGGER.error("Unable to flush pending write requests", ex);
        }
    }
1074103
def do_handshake(self):
        

        _logger.debug("Initiating handshake...")
        try:
            self._wrap_socket_library_call(
                lambda: SSL_do_handshake(self._ssl.value),
                ERR_HANDSHAKE_TIMEOUT)
        except openssl_error() as err:
            if err.ssl_error == SSL_ERROR_SYSCALL and err.result == -1:
                raise_ssl_error(ERR_PORT_UNREACHABLE, err)
            raise
        self._handshake_done = True
        _logger.debug("...completed handshake")
375025
def ensure_header(self, header: BlockHeader=None) -> BlockHeader:
        
        if header is None:
            head = self.get_canonical_head()
            return self.create_header_from_parent(head)
        else:
            return header
932323
def _fiss_agent_header(headers=None):
    
    _set_session()

    fiss_headers = {"User-Agent" : FISS_USER_AGENT}
    if headers is not None:
        fiss_headers.update(headers)
    return fiss_headers
334943
def negotiate_header(url):
    
    hostname = urlparse(url).hostname
    _, krb_context = kerberos.authGSSClientInit('HTTP@%s' % hostname)
    # authGSSClientStep goes over the network to the KDC (ie blocking).
    yield threads.deferToThread(kerberos.authGSSClientStep,
                                krb_context, '')
    negotiate_details = kerberos.authGSSClientResponse(krb_context)
    defer.returnValue('Negotiate ' + negotiate_details)
774997
def _process_server_headers(
        self, key: Union[str, bytes], headers: httputil.HTTPHeaders
    ) -> None:
        
        assert headers["Upgrade"].lower() == "websocket"
        assert headers["Connection"].lower() == "upgrade"
        accept = self.compute_accept_value(key)
        assert headers["Sec-Websocket-Accept"] == accept

        extensions = self._parse_extensions_header(headers)
        for ext in extensions:
            if ext[0] == "permessage-deflate" and self._compression_options is not None:
                self._create_compressors("client", ext[1])
            else:
                raise ValueError("unsupported extension %r", ext)

        self.selected_subprotocol = headers.get("Sec-WebSocket-Protocol", None)
1333943
async def accept(
            self,
            headers: Optional[Union[dict, CIMultiDict, Headers]] = None,
            subprotocol: Optional[str] = None,
    ) -> None:
        
        if headers is None:
            headers_ = Headers()
        else:
            headers_ = Headers(headers)
        await self._accept(headers_, subprotocol)
1354204
public HandshakerResp send(HandshakerReq req) throws InterruptedException, IOException {
    maybeThrowIoException();
    if (!responseQueue.isEmpty()) {
      throw new IOException("Received an unexpected response.");
    }
    writer.onNext(req);
    Optional<HandshakerResp> result = responseQueue.take();
    if (!result.isPresent()) {
      maybeThrowIoException();
    }
    return result.get();
  }
997002
def negotiate(cls, headers):
        
        # set lower keys
        headers = {k.lower(): v for k, v in headers.items()}

        accept = headers.get('accept', "*/*")

        parsed_accept = accept.split(";")
        parsed_accept = [i.strip() for i in parsed_accept]

        # Protobuffer (only one version)
        if all([i in parsed_accept for i in cls.PROTOBUF['default']]):
            return ProtobufFormat
        elif all([i in parsed_accept for i in cls.PROTOBUF['text']]):
            return ProtobufTextFormat
        # Text 0.0.4
        elif all([i in parsed_accept for i in cls.TEXT['0.0.4']]):
            return TextFormat
        # Text (Default)
        elif all([i in parsed_accept for i in cls.TEXT['default']]):
            return TextFormat
        # Default
        else:
            return cls.FALLBACK