Debian Codegraph @

docs/faq/server.rst

raw
1 Server
2 ======
3
4 .. currentmodule:: websockets.asyncio.server
5
6 .. admonition:: This FAQ is written for the new :mod:`asyncio` implementation.
7 :class: tip
8
9 Answers are also valid for the legacy :mod:`asyncio` implementation.
10
11 They translate to the :mod:`threading` implementation by removing ``await``
12 and ``async`` keywords and by using a :class:`~threading.Thread` instead of
13 a :class:`~asyncio.Task` for concurrent execution.
14
15 Why does the server close the connection prematurely?
16 -----------------------------------------------------
17
18 Your connection handler exits prematurely. Wait for the work to be finished
19 before returning.
20
21 For example, if your handler has a structure similar to::
22
23 async def handler(websocket):
24 asyncio.create_task(do_some_work())
25
26 change it to::
27
28 async def handler(websocket):
29 await do_some_work()
30
31 Why does the server close the connection after one message?
32 -----------------------------------------------------------
33
34 Your connection handler exits after processing one message. Write a loop to
35 process multiple messages.
36
37 For example, if your handler looks like this::
38
39 async def handler(websocket):
40 print(websocket.recv())
41
42 change it like this::
43
44 async def handler(websocket):
45 async for message in websocket:
46 print(message)
47
48 If you have prior experience with an API that relies on callbacks, you may
49 assume that ``handler()`` is executed every time a message is received. The API
50 of websockets relies on coroutines instead.
51
52 The handler coroutine is started when a new connection is established. Then, it
53 is responsible for receiving or sending messages throughout the lifetime of that
54 connection.
55
56 Why can only one client connect at a time?
57 ------------------------------------------
58
59 Your connection handler blocks the event loop. Look for blocking calls.
60
61 Any call that may take some time must be asynchronous.
62
63 For example, this connection handler prevents the event loop from running during
64 one second::
65
66 async def handler(websocket):
67 time.sleep(1)
68 ...
69
70 Change it to::
71
72 async def handler(websocket):
73 await asyncio.sleep(1)
74 ...
75
76 In addition, calling a coroutine doesn't guarantee that it will yield control to
77 the event loop.
78
79 For example, this connection handler blocks the event loop by sending messages
80 continuously::
81
82 async def handler(websocket):
83 while True:
84 await websocket.send("firehose!")
85
86 :meth:`~ServerConnection.send` completes synchronously as long as there's space
87 in send buffers. The event loop never runs. (This pattern is uncommon in
88 real-world applications. It occurs mostly in toy programs.)
89
90 You can avoid the issue by yielding control to the event loop explicitly::
91
92 async def handler(websocket):
93 while True:
94 await websocket.send("firehose!")
95 await asyncio.sleep(0)
96
97 All this is part of learning asyncio. It isn't specific to websockets.
98
99 See also Python's documentation about `running blocking code`_.
100
101 .. _running blocking code: https://docs.python.org/3/library/asyncio-dev.html#running-blocking-code
102
103 .. _send-message-to-all-users:
104
105 How do I send a message to all users?
106 -------------------------------------
107
108 Call :func:`broadcast`::
109
110 from websockets.asyncio.server import broadcast
111
112 broadcast(server.connections, message)
113
114 If you're running multiple server processes, execute :func:`broadcast` in each
115 process.
116
117 .. _send-message-to-single-user:
118
119 How do I send a message to a single user?
120 -----------------------------------------
121
122 Record connections in a global variable, keyed by user identifier::
123
124 import collections
125
126 CONNECTIONS = collections.defaultdict(set)
127
128 async def handler(websocket):
129 user_id = ... # identify user in your app's context
130 CONNECTIONS[user_id].add(websocket)
131 try:
132 await websocket.wait_closed()
133 finally:
134 CONNECTIONS[user_id].remove(websocket)
135
136 Then, call :meth:`~ServerConnection.send`::
137
138 async def message_user(user_id, message):
139 for websocket in CONNECTIONS[user_id]:
140 try:
141 await websocket.send(message)
142 except websockets.exceptions.ConnectionClosed
143 pass
144
145 or just :func:`broadcast`::
146
147 from websockets.asyncio.server import broadcast
148
149 def message_user(user_id, message):
150 broadcast(CONNECTIONS[user_id], message)
151
152 If you're running multiple server processes, execute ``message_user`` in each
153 process.
154
155 When you reach a scale where server processes cannot keep up with the stream of
156 all messages, you need a better architecture. For example, you could deploy an
157 external publish / subscribe system such as Redis_. Server processes would
158 subscribe their clients. Then, they would receive messages only for the
159 connections that they're managing.
160
161 .. _Redis: https://redis.io/
162
163 How do I send a message to a channel, a topic, or some users?
164 -------------------------------------------------------------
165
166 websockets doesn't provide built-in publish / subscribe functionality.
167
168 Record connections in a global variable, keyed by user identifier, as shown in
169 :ref:`How do I send a message to a single user?<send-message-to-single-user>`
170
171 Then, build the set of recipients and broadcast the message to them, as shown in
172 :ref:`How do I send a message to all users?<send-message-to-all-users>`
173
174 :doc:`../howto/django` contains a complete implementation of this pattern.
175
176 Again, as you scale, you may reach the performance limits of a basic in-process
177 implementation. You may need an external publish / subscribe system like Redis_.
178
179 .. _Redis: https://redis.io/
180
181 How do I pass arguments to the connection handler?
182 --------------------------------------------------
183
184 You can bind additional arguments to the connection handler with
185 :func:`functools.partial`::
186
187 import functools
188
189 async def handler(websocket, extra_argument):
190 ...
191
192 bound_handler = functools.partial(handler, extra_argument=42)
193
194 Another way to achieve this result is to define the ``handler`` coroutine in
195 a scope where the ``extra_argument`` variable exists instead of injecting it
196 through an argument.
197
198 How do I access the request path?
199 ---------------------------------
200
201 It is available in the :attr:`~ServerConnection.request` object.
202
203 Refer to the :doc:`routing guide <../topics/routing>` for details on how to
204 route connections to different handlers depending on the request path.
205
206 How do I access HTTP headers?
207 -----------------------------
208
209 You can access HTTP headers during the WebSocket handshake by providing a
210 ``process_request`` callable or coroutine::
211
212 def process_request(connection, request):
213 authorization = request.headers["Authorization"]
214 ...
215
216 server = await serve(handler, process_request=process_request)
217
218 Once the connection is established, HTTP headers are available in the
219 :attr:`~ServerConnection.request` and :attr:`~ServerConnection.response`
220 objects::
221
222 async def handler(websocket):
223 authorization = websocket.request.headers["Authorization"]
224
225 How do I set HTTP headers?
226 --------------------------
227
228 To set the ``Sec-WebSocket-Extensions`` or ``Sec-WebSocket-Protocol`` headers in
229 the WebSocket handshake response, use the ``extensions`` or ``subprotocols``
230 arguments of :func:`~serve`.
231
232 To override the ``Server`` header, use the ``server_header`` argument. Set it to
233 :obj:`None` to remove the header.
234
235 To set other HTTP headers, provide a ``process_response`` callable or
236 coroutine::
237
238 def process_response(connection, request, response):
239 response.headers["X-Blessing"] = "May the network be with you"
240
241 server = await serve(handler, process_response=process_response)
242
243 How do I get the IP address of the client?
244 ------------------------------------------
245
246 It's available in :attr:`~ServerConnection.remote_address`::
247
248 async def handler(websocket):
249 remote_ip = websocket.remote_address[0]
250
251 How do I set the IP addresses that my server listens on?
252 --------------------------------------------------------
253
254 Use the ``host`` argument of :meth:`~serve`::
255
256 server = await serve(handler, host="192.168.0.1", port=8080)
257
258 :func:`~serve` accepts the same arguments as
259 :meth:`~asyncio.loop.create_server` and passes them through.
260
261 What does ``OSError: [Errno 99] error while attempting to bind on address ('::1', 80, 0, 0): address not available`` mean?
262 --------------------------------------------------------------------------------------------------------------------------
263
264 You are calling :func:`~serve` without a ``host`` argument in a context where
265 IPv6 isn't available.
266
267 To listen only on IPv4, specify ``host="0.0.0.0"`` or ``family=socket.AF_INET``.
268
269 Refer to the documentation of :meth:`~asyncio.loop.create_server` for details.
270
271 How do I close a connection?
272 ----------------------------
273
274 websockets takes care of closing the connection when the handler exits.
275
276 How do I stop a server?
277 -----------------------
278
279 Depending on how you started it, you can:
280
281 * Exit the :func:`~serve` context manager.
282 * Call the :meth:`~Server.close` method.
283 * Cancel the :meth:`~Server.serve_forever` coroutine.
284
285 Await :meth:`~Server.wait_closed` to wait for the server to be fully closed.
286
287 Here's an example that terminates cleanly when it receives SIGTERM on Unix:
288
289 .. literalinclude:: ../../example/faq/shutdown_server.py
290 :emphasize-lines: 14-16
291
292 How do I stop a server while keeping existing connections open?
293 ---------------------------------------------------------------
294
295 Call the server's :meth:`~Server.close` method with ``close_connections=False``.
296
297 Here's how to adapt the example just above:
298
299 .. code-block:: python
300 :emphasize-lines: 5-8
301
302 async def main():
303 server = await serve(handler, "localhost", 8765)
304 # Close the server when receiving SIGTERM.
305 loop = asyncio.get_running_loop()
306 loop.add_signal_handler(
307 signal.SIGTERM,
308 functools.partial(server.close, close_connections=False),
309 )
310 await server.wait_closed()
311
312 The server will exit after all clients disconnect.
313
314 How do I implement a health check?
315 ----------------------------------
316
317 Intercept requests with the ``process_request`` hook. When a request is sent to
318 the health check endpoint, treat is as an HTTP request and return a response:
319
320 .. literalinclude:: ../../example/faq/health_check_server.py
321 :emphasize-lines: 7-9,16
322
323 :meth:`~ServerConnection.respond` makes it easy to send a plain text response.
324 You can also construct a :class:`~websockets.http11.Response` object directly.
325
326 How do I run HTTP and WebSocket servers on the same port?
327 ---------------------------------------------------------
328
329 You don't.
330
331 HTTP and WebSocket have widely different operational characteristics. Running
332 them with the same server becomes inconvenient when you scale.
333
334 Providing an HTTP server is out of scope for websockets. It only aims at
335 providing a WebSocket server.
336
337 There's limited support for returning HTTP responses with the
338 ``process_request`` hook.
339
340 If you need more, pick an HTTP server and run it separately.
341
342 Alternatively, pick an HTTP framework that builds on top of ``websockets`` to
343 support WebSocket connections, like Sanic_.
344
345 .. _Sanic: https://sanicframework.org/en/