| 1 |
#! /usr/bin/env python |
| 2 |
"""Drive several WebSocket connections concurrently with CurlMulti. |
| 3 |
|
| 4 |
The handshake runs through the multi interface; once every handle has |
| 5 |
completed the upgrade, we select() on the underlying sockets and use |
| 6 |
ws_send / ws_recv on whichever handle becomes readable. |
| 7 |
""" |
| 8 |
|
| 9 |
import select |
| 10 |
import pycurl |
| 11 |
|
| 12 |
URLS = ["wss://echo.websocket.events/"] * 3 |
| 13 |
|
| 14 |
handles = [] |
| 15 |
m = pycurl.CurlMulti() |
| 16 |
for url in URLS: |
| 17 |
c = pycurl.Curl() |
| 18 |
c.setopt(c.URL, url) |
| 19 |
c.setopt(c.CONNECT_ONLY, 2) |
| 20 |
m.add_handle(c) |
| 21 |
handles.append(c) |
| 22 |
|
| 23 |
# Drive the handshakes concurrently via the multi interface. |
| 24 |
_, num_handles = m.perform() |
| 25 |
while num_handles: |
| 26 |
m.select(1.0) |
| 27 |
_, num_handles = m.perform() |
| 28 |
|
| 29 |
# Every handle has finished the WebSocket upgrade — collect results. |
| 30 |
_, done, failed = m.info_read() |
| 31 |
if failed: |
| 32 |
raise RuntimeError("WebSocket handshake failed: %r" % (failed,)) |
| 33 |
|
| 34 |
fd_to_curl = {c.getinfo(pycurl.ACTIVESOCKET): c for c in handles} |
| 35 |
for c in handles: |
| 36 |
c.ws_send("hello") |
| 37 |
|
| 38 |
# Read one reply from each handle. A real application would keep |
| 39 |
# looping on select() for as long as it has work to do; this demo |
| 40 |
# simply waits until each connection has produced its echoed frame. |
| 41 |
pending = set(fd_to_curl) |
| 42 |
while pending: |
| 43 |
readable, _, _ = select.select(list(pending), [], [], 5.0) |
| 44 |
if not readable: |
| 45 |
raise TimeoutError("no reply within 5s for handles %r" % (pending,)) |
| 46 |
for fd in readable: |
| 47 |
data, meta = fd_to_curl[fd].ws_recv(4096) |
| 48 |
print(fd, data, "flags=", meta.flags) |
| 49 |
pending.discard(fd) |
| 50 |
|
| 51 |
for c in handles: |
| 52 |
c.ws_close() |
| 53 |
m.remove_handle(c) |
| 54 |
c.close() |
| 55 |
m.close() |