Debian Codegraph @

testing/web-platform/tests/tools/third_party/websockets/docs/intro/tutorial1.rst

raw
1 Part 1 - Send & receive
2 =======================
3
4 .. currentmodule:: websockets
5
6 In this tutorial, you're going to build a web-based `Connect Four`_ game.
7
8 .. _Connect Four: https://en.wikipedia.org/wiki/Connect_Four
9
10 The web removes the constraint of being in the same room for playing a game.
11 Two players can connect over of the Internet, regardless of where they are,
12 and play in their browsers.
13
14 When a player makes a move, it should be reflected immediately on both sides.
15 This is difficult to implement over HTTP due to the request-response style of
16 the protocol.
17
18 Indeed, there is no good way to be notified when the other player makes a
19 move. Workarounds such as polling or long-polling introduce significant
20 overhead.
21
22 Enter `WebSocket <websocket>`_.
23
24 The WebSocket protocol provides two-way communication between a browser and a
25 server over a persistent connection. That's exactly what you need to exchange
26 moves between players, via a server.
27
28 .. admonition:: This is the first part of the tutorial.
29
30 * In this :doc:`first part <tutorial1>`, you will create a server and
31 connect one browser; you can play if you share the same browser.
32 * In the :doc:`second part <tutorial2>`, you will connect a second
33 browser; you can play from different browsers on a local network.
34 * In the :doc:`third part <tutorial3>`, you will deploy the game to the
35 web; you can play from any browser connected to the Internet.
36
37 Prerequisites
38 -------------
39
40 This tutorial assumes basic knowledge of Python and JavaScript.
41
42 If you're comfortable with :doc:`virtual environments <python:tutorial/venv>`,
43 you can use one for this tutorial. Else, don't worry: websockets doesn't have
44 any dependencies; it shouldn't create trouble in the default environment.
45
46 If you haven't installed websockets yet, do it now:
47
48 .. code-block:: console
49
50 $ pip install websockets
51
52 Confirm that websockets is installed:
53
54 .. code-block:: console
55
56 $ python -m websockets --version
57
58 .. admonition:: This tutorial is written for websockets |release|.
59 :class: tip
60
61 If you installed another version, you should switch to the corresponding
62 version of the documentation.
63
64 Download the starter kit
65 ------------------------
66
67 Create a directory and download these three files:
68 :download:`connect4.js <../../example/tutorial/start/connect4.js>`,
69 :download:`connect4.css <../../example/tutorial/start/connect4.css>`,
70 and :download:`connect4.py <../../example/tutorial/start/connect4.py>`.
71
72 The JavaScript module, along with the CSS file, provides a web-based user
73 interface. Here's its API.
74
75 .. js:module:: connect4
76
77 .. js:data:: PLAYER1
78
79 Color of the first player.
80
81 .. js:data:: PLAYER2
82
83 Color of the second player.
84
85 .. js:function:: createBoard(board)
86
87 Draw a board.
88
89 :param board: DOM element containing the board; must be initially empty.
90
91 .. js:function:: playMove(board, player, column, row)
92
93 Play a move.
94
95 :param board: DOM element containing the board.
96 :param player: :js:data:`PLAYER1` or :js:data:`PLAYER2`.
97 :param column: between ``0`` and ``6``.
98 :param row: between ``0`` and ``5``.
99
100 The Python module provides a class to record moves and tell when a player
101 wins. Here's its API.
102
103 .. module:: connect4
104
105 .. data:: PLAYER1
106 :value: "red"
107
108 Color of the first player.
109
110 .. data:: PLAYER2
111 :value: "yellow"
112
113 Color of the second player.
114
115 .. class:: Connect4
116
117 A Connect Four game.
118
119 .. method:: play(player, column)
120
121 Play a move.
122
123 :param player: :data:`~connect4.PLAYER1` or :data:`~connect4.PLAYER2`.
124 :param column: between ``0`` and ``6``.
125 :returns: Row where the checker lands, between ``0`` and ``5``.
126 :raises RuntimeError: if the move is illegal.
127
128 .. attribute:: moves
129
130 List of moves played during this game, as ``(player, column, row)``
131 tuples.
132
133 .. attribute:: winner
134
135 :data:`~connect4.PLAYER1` or :data:`~connect4.PLAYER2` if they
136 won; :obj:`None` if the game is still ongoing.
137
138 .. currentmodule:: websockets
139
140 Bootstrap the web UI
141 --------------------
142
143 Create an ``index.html`` file next to ``connect4.js`` and ``connect4.css``
144 with this content:
145
146 .. literalinclude:: ../../example/tutorial/step1/index.html
147 :language: html
148
149 This HTML page contains an empty ``<div>`` element where you will draw the
150 Connect Four board. It loads a ``main.js`` script where you will write all
151 your JavaScript code.
152
153 Create a ``main.js`` file next to ``index.html``. In this script, when the
154 page loads, draw the board:
155
156 .. code-block:: javascript
157
158 import { createBoard, playMove } from "./connect4.js";
159
160 window.addEventListener("DOMContentLoaded", () => {
161 // Initialize the UI.
162 const board = document.querySelector(".board");
163 createBoard(board);
164 });
165
166 Open a shell, navigate to the directory containing these files, and start an
167 HTTP server:
168
169 .. code-block:: console
170
171 $ python -m http.server
172
173 Open http://localhost:8000/ in a web browser. The page displays an empty board
174 with seven columns and six rows. You will play moves in this board later.
175
176 Bootstrap the server
177 --------------------
178
179 Create an ``app.py`` file next to ``connect4.py`` with this content:
180
181 .. code-block:: python
182
183 #!/usr/bin/env python
184
185 import asyncio
186
187 import websockets
188
189
190 async def handler(websocket):
191 while True:
192 message = await websocket.recv()
193 print(message)
194
195
196 async def main():
197 async with websockets.serve(handler, "", 8001):
198 await asyncio.Future() # run forever
199
200
201 if __name__ == "__main__":
202 asyncio.run(main())
203
204 The entry point of this program is ``asyncio.run(main())``. It creates an
205 asyncio event loop, runs the ``main()`` coroutine, and shuts down the loop.
206
207 The ``main()`` coroutine calls :func:`~server.serve` to start a websockets
208 server. :func:`~server.serve` takes three positional arguments:
209
210 * ``handler`` is a coroutine that manages a connection. When a client
211 connects, websockets calls ``handler`` with the connection in argument.
212 When ``handler`` terminates, websockets closes the connection.
213 * The second argument defines the network interfaces where the server can be
214 reached. Here, the server listens on all interfaces, so that other devices
215 on the same local network can connect.
216 * The third argument is the port on which the server listens.
217
218 Invoking :func:`~server.serve` as an asynchronous context manager, in an
219 ``async with`` block, ensures that the server shuts down properly when
220 terminating the program.
221
222 For each connection, the ``handler()`` coroutine runs an infinite loop that
223 receives messages from the browser and prints them.
224
225 Open a shell, navigate to the directory containing ``app.py``, and start the
226 server:
227
228 .. code-block:: console
229
230 $ python app.py
231
232 This doesn't display anything. Hopefully the WebSocket server is running.
233 Let's make sure that it works. You cannot test the WebSocket server with a
234 web browser like you tested the HTTP server. However, you can test it with
235 websockets' interactive client.
236
237 Open another shell and run this command:
238
239 .. code-block:: console
240
241 $ python -m websockets ws://localhost:8001/
242
243 You get a prompt. Type a message and press "Enter". Switch to the shell where
244 the server is running and check that the server received the message. Good!
245
246 Exit the interactive client with Ctrl-C or Ctrl-D.
247
248 Now, if you look at the console where you started the server, you can see the
249 stack trace of an exception:
250
251 .. code-block:: pytb
252
253 connection handler failed
254 Traceback (most recent call last):
255 ...
256 File "app.py", line 22, in handler
257 message = await websocket.recv()
258 ...
259 websockets.exceptions.ConnectionClosedOK: received 1000 (OK); then sent 1000 (OK)
260
261 Indeed, the server was waiting for the next message
262 with :meth:`~legacy.protocol.WebSocketCommonProtocol.recv` when the client
263 disconnected. When this happens, websockets raises
264 a :exc:`~exceptions.ConnectionClosedOK` exception to let you know that you
265 won't receive another message on this connection.
266
267 This exception creates noise in the server logs, making it more difficult to
268 spot real errors when you add functionality to the server. Catch it in the
269 ``handler()`` coroutine:
270
271 .. code-block:: python
272
273 async def handler(websocket):
274 while True:
275 try:
276 message = await websocket.recv()
277 except websockets.ConnectionClosedOK:
278 break
279 print(message)
280
281 Stop the server with Ctrl-C and start it again:
282
283 .. code-block:: console
284
285 $ python app.py
286
287 .. admonition:: You must restart the WebSocket server when you make changes.
288 :class: tip
289
290 The WebSocket server loads the Python code in ``app.py`` then serves every
291 WebSocket request with this version of the code. As a consequence,
292 changes to ``app.py`` aren't visible until you restart the server.
293
294 This is unlike the HTTP server that you started earlier with ``python -m
295 http.server``. For every request, this HTTP server reads the target file
296 and sends it. That's why changes are immediately visible.
297
298 It is possible to :doc:`restart the WebSocket server automatically
299 <../howto/autoreload>` but this isn't necessary for this tutorial.
300
301 Try connecting and disconnecting the interactive client again.
302 The :exc:`~exceptions.ConnectionClosedOK` exception doesn't appear anymore.
303
304 This pattern is so common that websockets provides a shortcut for iterating
305 over messages received on the connection until the client disconnects:
306
307 .. code-block:: python
308
309 async def handler(websocket):
310 async for message in websocket:
311 print(message)
312
313 Restart the server and check with the interactive client that its behavior
314 didn't change.
315
316 At this point, you bootstrapped a web application and a WebSocket server.
317 Let's connect them.
318
319 Transmit from browser to server
320 -------------------------------
321
322 In JavaScript, you open a WebSocket connection as follows:
323
324 .. code-block:: javascript
325
326 const websocket = new WebSocket("ws://localhost:8001/");
327
328 Before you exchange messages with the server, you need to decide their format.
329 There is no universal convention for this.
330
331 Let's use JSON objects with a ``type`` key identifying the type of the event
332 and the rest of the object containing properties of the event.
333
334 Here's an event describing a move in the middle slot of the board:
335
336 .. code-block:: javascript
337
338 const event = {type: "play", column: 3};
339
340 Here's how to serialize this event to JSON and send it to the server:
341
342 .. code-block:: javascript
343
344 websocket.send(JSON.stringify(event));
345
346 Now you have all the building blocks to send moves to the server.
347
348 Add this function to ``main.js``:
349
350 .. literalinclude:: ../../example/tutorial/step1/main.js
351 :language: js
352 :start-at: function sendMoves
353 :end-before: window.addEventListener
354
355 ``sendMoves()`` registers a listener for ``click`` events on the board. The
356 listener figures out which column was clicked, builds a event of type
357 ``"play"``, serializes it, and sends it to the server.
358
359 Modify the initialization to open the WebSocket connection and call the
360 ``sendMoves()`` function:
361
362 .. code-block:: javascript
363
364 window.addEventListener("DOMContentLoaded", () => {
365 // Initialize the UI.
366 const board = document.querySelector(".board");
367 createBoard(board);
368 // Open the WebSocket connection and register event handlers.
369 const websocket = new WebSocket("ws://localhost:8001/");
370 sendMoves(board, websocket);
371 });
372
373 Check that the HTTP server and the WebSocket server are still running. If you
374 stopped them, here are the commands to start them again:
375
376 .. code-block:: console
377
378 $ python -m http.server
379
380 .. code-block:: console
381
382 $ python app.py
383
384 Refresh http://localhost:8000/ in your web browser. Click various columns in
385 the board. The server receives messages with the expected column number.
386
387 There isn't any feedback in the board because you haven't implemented that
388 yet. Let's do it.
389
390 Transmit from server to browser
391 -------------------------------
392
393 In JavaScript, you receive WebSocket messages by listening to ``message``
394 events. Here's how to receive a message from the server and deserialize it
395 from JSON:
396
397 .. code-block:: javascript
398
399 websocket.addEventListener("message", ({ data }) => {
400 const event = JSON.parse(data);
401 // do something with event
402 });
403
404 You're going to need three types of messages from the server to the browser:
405
406 .. code-block:: javascript
407
408 {type: "play", player: "red", column: 3, row: 0}
409 {type: "win", player: "red"}
410 {type: "error", message: "This slot is full."}
411
412 The JavaScript code receiving these messages will dispatch events depending on
413 their type and take appropriate action. For example, it will react to an
414 event of type ``"play"`` by displaying the move on the board with
415 the :js:func:`~connect4.playMove` function.
416
417 Add this function to ``main.js``:
418
419 .. literalinclude:: ../../example/tutorial/step1/main.js
420 :language: js
421 :start-at: function showMessage
422 :end-before: function sendMoves
423
424 .. admonition:: Why does ``showMessage`` use ``window.setTimeout``?
425 :class: hint
426
427 When :js:func:`playMove` modifies the state of the board, the browser
428 renders changes asynchronously. Conversely, ``window.alert()`` runs
429 synchronously and blocks rendering while the alert is visible.
430
431 If you called ``window.alert()`` immediately after :js:func:`playMove`,
432 the browser could display the alert before rendering the move. You could
433 get a "Player red wins!" alert without seeing red's last move.
434
435 We're using ``window.alert()`` for simplicity in this tutorial. A real
436 application would display these messages in the user interface instead.
437 It wouldn't be vulnerable to this problem.
438
439 Modify the initialization to call the ``receiveMoves()`` function:
440
441 .. literalinclude:: ../../example/tutorial/step1/main.js
442 :language: js
443 :start-at: window.addEventListener
444
445 At this point, the user interface should receive events properly. Let's test
446 it by modifying the server to send some events.
447
448 Sending an event from Python is quite similar to JavaScript:
449
450 .. code-block:: python
451
452 event = {"type": "play", "player": "red", "column": 3, "row": 0}
453 await websocket.send(json.dumps(event))
454
455 .. admonition:: Don't forget to serialize the event with :func:`json.dumps`.
456 :class: tip
457
458 Else, websockets raises ``TypeError: data is a dict-like object``.
459
460 Modify the ``handler()`` coroutine in ``app.py`` as follows:
461
462 .. code-block:: python
463
464 import json
465
466 from connect4 import PLAYER1, PLAYER2
467
468 async def handler(websocket):
469 for player, column, row in [
470 (PLAYER1, 3, 0),
471 (PLAYER2, 3, 1),
472 (PLAYER1, 4, 0),
473 (PLAYER2, 4, 1),
474 (PLAYER1, 2, 0),
475 (PLAYER2, 1, 0),
476 (PLAYER1, 5, 0),
477 ]:
478 event = {
479 "type": "play",
480 "player": player,
481 "column": column,
482 "row": row,
483 }
484 await websocket.send(json.dumps(event))
485 await asyncio.sleep(0.5)
486 event = {
487 "type": "win",
488 "player": PLAYER1,
489 }
490 await websocket.send(json.dumps(event))
491
492 Restart the WebSocket server and refresh http://localhost:8000/ in your web
493 browser. Seven moves appear at 0.5 second intervals. Then an alert announces
494 the winner.
495
496 Good! Now you know how to communicate both ways.
497
498 Once you plug the game engine to process moves, you will have a fully
499 functional game.
500
501 Add the game logic
502 ------------------
503
504 In the ``handler()`` coroutine, you're going to initialize a game:
505
506 .. code-block:: python
507
508 from connect4 import Connect4
509
510 async def handler(websocket):
511 # Initialize a Connect Four game.
512 game = Connect4()
513
514 ...
515
516 Then, you're going to iterate over incoming messages and take these steps:
517
518 * parse an event of type ``"play"``, the only type of event that the user
519 interface sends;
520 * play the move in the board with the :meth:`~connect4.Connect4.play` method,
521 alternating between the two players;
522 * if :meth:`~connect4.Connect4.play` raises :exc:`RuntimeError` because the
523 move is illegal, send an event of type ``"error"``;
524 * else, send an event of type ``"play"`` to tell the user interface where the
525 checker lands;
526 * if the move won the game, send an event of type ``"win"``.
527
528 Try to implement this by yourself!
529
530 Keep in mind that you must restart the WebSocket server and reload the page in
531 the browser when you make changes.
532
533 When it works, you can play the game from a single browser, with players
534 taking alternate turns.
535
536 .. admonition:: Enable debug logs to see all messages sent and received.
537 :class: tip
538
539 Here's how to enable debug logs:
540
541 .. code-block:: python
542
543 import logging
544
545 logging.basicConfig(format="%(message)s", level=logging.DEBUG)
546
547 If you're stuck, a solution is available at the bottom of this document.
548
549 Summary
550 -------
551
552 In this first part of the tutorial, you learned how to:
553
554 * build and run a WebSocket server in Python with :func:`~server.serve`;
555 * receive a message in a connection handler
556 with :meth:`~server.WebSocketServerProtocol.recv`;
557 * send a message in a connection handler
558 with :meth:`~server.WebSocketServerProtocol.send`;
559 * iterate over incoming messages with ``async for
560 message in websocket: ...``;
561 * open a WebSocket connection in JavaScript with the ``WebSocket`` API;
562 * send messages in a browser with ``WebSocket.send()``;
563 * receive messages in a browser by listening to ``message`` events;
564 * design a set of events to be exchanged between the browser and the server.
565
566 You can now play a Connect Four game in a browser, communicating over a
567 WebSocket connection with a server where the game logic resides!
568
569 However, the two players share a browser, so the constraint of being in the
570 same room still applies.
571
572 Move on to the :doc:`second part <tutorial2>` of the tutorial to break this
573 constraint and play from separate browsers.
574
575 Solution
576 --------
577
578 .. literalinclude:: ../../example/tutorial/step1/app.py
579 :caption: app.py
580 :language: python
581 :linenos:
582
583 .. literalinclude:: ../../example/tutorial/step1/index.html
584 :caption: index.html
585 :language: html
586 :linenos:
587
588 .. literalinclude:: ../../example/tutorial/step1/main.js
589 :caption: main.js
590 :language: js
591 :linenos: