How to use the wsproto.events.AcceptConnection function in wsproto

To help you get started, we’ve selected a few wsproto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-hyper / wsproto / test / test_upgrade.py View on Github external
request += b"Upgrade: WebSocket\r\n"
        request += b"Sec-WebSocket-Version: 13\r\n"
        request += b"Sec-WebSocket-Key: " + nonce + b"\r\n"
        request += (
            b"Sec-WebSocket-Extensions: "
            + ext.name.encode("ascii")
            + b"; "
            + offered_params.encode("ascii")
            + b"\r\n"
        )
        request += b"\r\n"

        ws.receive_bytes(request)
        event = next(ws.events())
        assert isinstance(event, Request)
        ws.send(AcceptConnection(extensions=[ext]))

        data = ws.bytes_to_send()
        response, headers = data.split(b"\r\n", 1)
        version, code, reason = response.split(b" ")
        headers = parse_headers(headers)

        assert ext.offered == "%s; %s" % (ext.name, offered_params)
        assert headers["sec-websocket-extensions"] == "%s; %s" % (ext.name, ext_params)
github python-hyper / wsproto / test / test_upgrade.py View on Github external
ws = WSConnection(SERVER)

        nonce = bytes(random.getrandbits(8) for x in range(0, 16))
        nonce = base64.b64encode(nonce)
        headers = [
            (b"Host", b"frob.nitz"),
            (b"Connection", b"Upgrade"),
            (b"Upgrade", b"WebSocket"),
            (b"Sec-WebSocket-Version", b"13"),
            (b"Sec-WebSocket-Key", nonce),
        ]

        ws.initiate_upgrade_connection(headers, "/fnord")
        event = next(ws.events())
        assert isinstance(event, Request)
        ws.send(AcceptConnection())

        data = ws.bytes_to_send()
        response, headers = data.split(b"\r\n", 1)
        version, code, reason = response.split(b" ")
        headers = parse_headers(headers)

        accept_token = ws._generate_accept_token(nonce)

        assert int(code) == 101
        assert headers["connection"].lower() == "upgrade"
        assert headers["upgrade"].lower() == "websocket"
        assert headers["sec-websocket-accept"] == accept_token.decode("ascii")
github trollfot / trinket / src / trinket / testing.py View on Github external
async def connect(self, path, host, port):
        await self.socket.connect((host, port))
        request = Request(host=f'{host}:{port}', target=path)
        await self.socket.sendall(self.protocol.send(request))
        upgrade_response = await self.socket.recv(8096)
        self.protocol.receive_data(upgrade_response)
        event = next(self.protocol.events())
        if not isinstance(event, AcceptConnection):
            raise Exception('Websocket handshake failed.')
github python-hyper / wsproto / compliance / test_client.py View on Github external
connection = WSConnection(CLIENT)
    sock = socket.socket()
    sock.connect((uri.hostname, uri.port or 80))

    sock.sendall(
        connection.send(
            Request(host=uri.netloc, target="%s?%s" % (uri.path, uri.query))
        )
    )
    closed = False

    while not closed:
        data = sock.recv(65535)
        connection.receive_data(data)
        for event in connection.events():
            if isinstance(event, AcceptConnection):
                sock.sendall(
                    connection.send(CloseConnection(code=CloseReason.NORMAL_CLOSURE))
                )
                try:
                    sock.close()
                except CONNECTION_EXCEPTIONS:
                    pass
                finally:
                    closed = True
github pgjones / hypercorn / tests / trio / test_sanity.py View on Github external
async def test_http1_websocket(nursery: trio._core._run.Nursery) -> None:
    client_stream, server_stream = trio.testing.memory_stream_pair()
    server_stream.socket = MockSocket()
    server = TCPServer(sanity_framework, Config(), server_stream)
    nursery.start_soon(server.run)
    client = wsproto.WSConnection(wsproto.ConnectionType.CLIENT)
    await client_stream.send_all(client.send(wsproto.events.Request(host="hypercorn", target="/")))
    client.receive_data(await client_stream.receive_some(1024))
    assert list(client.events()) == [
        wsproto.events.AcceptConnection(
            extra_headers=[
                (b"date", b"Thu, 01 Jan 1970 01:23:20 GMT"),
                (b"server", b"hypercorn-h11"),
            ]
        )
    ]
    await client_stream.send_all(client.send(wsproto.events.BytesMessage(data=SANITY_BODY)))
    client.receive_data(await client_stream.receive_some(1024))
    assert list(client.events()) == [wsproto.events.TextMessage(data="Hello & Goodbye")]
    await client_stream.send_all(client.send(wsproto.events.CloseConnection(code=1000)))
    client.receive_data(await client_stream.receive_some(1024))
    assert list(client.events()) == [wsproto.events.CloseConnection(code=1000, reason="")]
github python-hyper / wsproto / test / test_server.py View on Github external
method="GET",
                target="/",
                headers=[
                    (b"Host", b"localhost"),
                    (b"Connection", b"Keep-Alive, Upgrade"),
                    (b"Upgrade", b"WebSocket"),
                    (b"Sec-WebSocket-Version", b"13"),
                    (b"Sec-WebSocket-Key", nonce),
                ]
                + request_headers,
            )
        )
    )
    client.receive_data(
        server.send(
            AcceptConnection(
                extra_headers=accept_headers or [],
                subprotocol=subprotocol,
                extensions=extensions or [],
            )
        )
    )
    event = client.next_event()
    return event, nonce
github trollfot / trinket / src / trinket / websockets.py View on Github external
request.method, request.url)
        data += '\r\n'.join(
            ('{}: {}'.format(k, v)
             for k, v in request.headers.items())) + '\r\n\r\n'

        data = data.encode()

        try:
            self.protocol.receive_data(data)
        except RemoteProtocolError:
            raise HTTPError(HTTPStatus.BAD_REQUEST)
        else:
            event = next(self.protocol.events())
            if not isinstance(event, Request):
                raise HTTPError(HTTPStatus.BAD_REQUEST)
            data = self.protocol.send(AcceptConnection())
            await self.socket.sendall(data)
github python-hyper / wsproto / example / synchronous_client.py View on Github external
def handle_events(ws: WSConnection) -> None:
    for event in ws.events():
        if isinstance(event, AcceptConnection):
            print("WebSocket negotiation complete")
        elif isinstance(event, TextMessage):
            print("Received message: {}".format(event.data))
        elif isinstance(event, Pong):
            print("Received pong: {!r}".format(event.payload))
        else:
            raise Exception("Do not know how to handle event: " + str(event))
github python-hyper / wsproto / example / synchronous_server.py View on Github external
ws = WSConnection(ConnectionType.SERVER)
    running = True

    while running:
        # 1) Read data from network
        in_data = stream.recv(RECEIVE_BYTES)
        print("Received {} bytes".format(len(in_data)))
        ws.receive_data(in_data)

        # 2) Get new events and handle them
        out_data = b""
        for event in ws.events():
            if isinstance(event, Request):
                # Negotiate new WebSocket connection
                print("Accepting WebSocket upgrade")
                out_data += ws.send(AcceptConnection())
            elif isinstance(event, CloseConnection):
                # Print log message and break out
                print(
                    "Connection closed: code={} reason={}".format(
                        event.code, event.reason
                    )
                )
                out_data += ws.send(event.response())
                running = False
            elif isinstance(event, TextMessage):
                # Reverse text and send it back to wsproto
                print("Received request and sending response")
                out_data += ws.send(Message(data=event.data[::-1]))
            elif isinstance(event, Ping):
                # wsproto handles ping events for you by placing a pong frame in
                # the outgoing buffer. You should not call pong() unless you want to