Debian Codegraph @

docs/howto/patterns.rst

raw
1 Design a WebSocket application
2 ==============================
3
4 .. currentmodule:: websockets
5
6 WebSocket server or client applications follow common patterns. This guide
7 describes patterns that you're likely to implement in your application.
8
9 All examples are connection handlers for a server. However, they would also
10 apply to a client, assuming that ``websocket`` is a connection created with
11 :func:`~asyncio.client.connect`.
12
13 .. admonition:: WebSocket connections are long-lived.
14 :class: tip
15
16 You need a loop to process several messages during the lifetime of a
17 connection.
18
19 Consumer pattern
20 ----------------
21
22 To receive messages from the WebSocket connection::
23
24 async def consumer_handler(websocket):
25 async for message in websocket:
26 await consume(message)
27
28 In this example, ``consume()`` is a coroutine implementing your business logic
29 for processing a message received on the WebSocket connection.
30
31 Iteration terminates when the client disconnects.
32
33 Producer pattern
34 ----------------
35
36 To send messages to the WebSocket connection::
37
38 from websockets.exceptions import ConnectionClosed
39
40 async def producer_handler(websocket):
41 while True:
42 try:
43 message = await produce()
44 await websocket.send(message)
45 except ConnectionClosed:
46 break
47
48 In this example, ``produce()`` is a coroutine implementing your business logic
49 for generating the next message to send on the WebSocket connection.
50
51 Iteration terminates when the client disconnects because
52 :meth:`~asyncio.server.ServerConnection.send` raises a
53 :exc:`~exceptions.ConnectionClosed` exception, which breaks out of the ``while
54 True`` loop.
55
56 Consumer and producer
57 ---------------------
58
59 You can receive and send messages on the same WebSocket connection by
60 combining the consumer and producer patterns.
61
62 This requires running two tasks in parallel. The simplest option offered by
63 :mod:`asyncio` is::
64
65 import asyncio
66
67 async def handler(websocket):
68 await asyncio.gather(
69 consumer_handler(websocket),
70 producer_handler(websocket),
71 )
72
73 If a task terminates, :func:`~asyncio.gather` doesn't cancel the other task.
74 This can result in a situation where the producer keeps running after the
75 consumer finished, which may leak resources.
76
77 Here's a way to exit and close the WebSocket connection as soon as a task
78 terminates, after canceling the other task::
79
80 async def handler(websocket):
81 consumer_task = asyncio.create_task(consumer_handler(websocket))
82 producer_task = asyncio.create_task(producer_handler(websocket))
83 done, pending = await asyncio.wait(
84 [consumer_task, producer_task],
85 return_when=asyncio.FIRST_COMPLETED,
86 )
87 for task in pending:
88 task.cancel()
89
90 Multiple consumers
91 ------------------
92
93 You can run multiple consumer tasks to process incoming messages concurrently.
94 This helps when a single consumer can't keep up with incoming messages.
95
96 Use :class:`~asyncio.Queue` to distribute messages to multiple consumers in a
97 :class:`~asyncio.TaskGroup`::
98
99 import asyncio
100
101 async def worker(queue):
102 while True:
103 message = await queue.get()
104 await consume_slowly(message)
105 queue.task_done()
106
107
108 async def run_workers(queue, num_workers=16):
109 async with asyncio.TaskGroup() as task_group:
110 for _ in range(num_workers):
111 task_group.create_task(worker(queue))
112
113 async def handler(websocket):
114 queue = asyncio.Queue()
115 workers_task = asyncio.create_task(run_workers(queue))
116 try:
117 async for message in websocket:
118 await queue.put(message)
119 finally:
120 await queue.join()
121 workers_task.cancel()
122
123 Registration
124 ------------
125
126 To keep track of currently connected clients, you can register them when they
127 connect and unregister them when they disconnect::
128
129 connected = set()
130
131 async def handler(websocket):
132 # Register.
133 connected.add(websocket)
134 try:
135 # Broadcast a message to all connected clients.
136 broadcast(connected, "Hello!")
137 await asyncio.sleep(10)
138 finally:
139 # Unregister.
140 connected.remove(websocket)
141
142 This example maintains the set of connected clients in memory. This works as
143 long as you run a single process. It doesn't scale to multiple processes.
144
145 If you just need the set of connected clients, as in this example, use the
146 :attr:`~asyncio.server.Server.connections` property of the server. This pattern
147 is needed only when recording additional information about each client.
148
149 Publish–subscribe
150 -----------------
151
152 If you plan to run multiple processes and you want to communicate updates
153 between processes, then you must deploy a messaging system. You may find
154 publish-subscribe functionality useful.
155
156 A complete implementation of this idea with Redis is described in
157 the :doc:`Django integration guide <../howto/django>`.