Debian Codegraph @

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