forked from 0x676e67/wreq-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp2_websocket.py
More file actions
71 lines (53 loc) · 1.97 KB
/
http2_websocket.py
File metadata and controls
71 lines (53 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import asyncio
import datetime
import signal
import wreq
from wreq import Message, WebSocket
from wreq import exceptions
async def send_message(ws):
print("Starting to send messages...")
for i in range(20):
print(f"Sending: Message {i + 1}")
await ws.send(Message.from_text(f"Message {i + 1}"))
await asyncio.sleep(0.1)
async def recv_message(ws):
print("Starting to receive messages...")
while True:
try:
message = await ws.recv(timeout=datetime.timedelta(milliseconds=10))
print("Received: ", message)
if message is None:
print("Connection closed by server.")
break
if message.data == b"Message 20":
print("Closing connection...")
break
except exceptions.TimeoutError:
continue
"""
Run websocket server
To test this example:
git clone https://github.com/tokio-rs/axum && cd axum
cargo run -p example-websockets-http2
Then run this Python script to connect to the websocket server.
"""
async def main():
client = wreq.Client(tls_verify=False)
ws: WebSocket = await client.websocket("wss://127.0.0.1:3000/ws", force_http2=True)
async with ws:
print("Status Code: ", ws.status)
print("Version: ", ws.version)
print("Headers: ", ws.headers)
print("Remote Address: ", ws.remote_addr)
if ws.status == 200:
print("WebSocket connection established successfully.")
send_task = asyncio.create_task(send_message(ws))
receive_task = asyncio.create_task(recv_message(ws))
async def close():
await ws.close()
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda: asyncio.create_task(close()))
await asyncio.gather(send_task, receive_task)
if __name__ == "__main__":
asyncio.run(main())