| 1 |
Part 2 - Route & broadcast |
| 2 |
========================== |
| 3 |
|
| 4 |
.. currentmodule:: websockets |
| 5 |
|
| 6 |
.. admonition:: This is the second part of the tutorial. |
| 7 |
|
| 8 |
* In the :doc:`first part <tutorial1>`, you created a server and |
| 9 |
connected one browser; you could play if you shared the same browser. |
| 10 |
* In this :doc:`second part <tutorial2>`, you will connect a second |
| 11 |
browser; you can play from different browsers on a local network. |
| 12 |
* In the :doc:`third part <tutorial3>`, you will deploy the game to the |
| 13 |
web; you can play from any browser connected to the Internet. |
| 14 |
|
| 15 |
In the first part of the tutorial, you opened a WebSocket connection from a |
| 16 |
browser to a server and exchanged events to play moves. The state of the game |
| 17 |
was stored in an instance of the :class:`~connect4.Connect4` class, |
| 18 |
referenced as a local variable in the connection handler coroutine. |
| 19 |
|
| 20 |
Now you want to open two WebSocket connections from two separate browsers, one |
| 21 |
for each player, to the same server in order to play the same game. This |
| 22 |
requires moving the state of the game to a place where both connections can |
| 23 |
access it. |
| 24 |
|
| 25 |
Share game state |
| 26 |
---------------- |
| 27 |
|
| 28 |
As long as you're running a single server process, you can share state by |
| 29 |
storing it in a global variable. |
| 30 |
|
| 31 |
.. admonition:: What if you need to scale to multiple server processes? |
| 32 |
:class: hint |
| 33 |
|
| 34 |
In that case, you must design a way for the process that handles a given |
| 35 |
connection to be aware of relevant events for that client. This is often |
| 36 |
achieved with a publish / subscribe mechanism. |
| 37 |
|
| 38 |
How can you make two connection handlers agree on which game they're playing? |
| 39 |
When the first player starts a game, you give it an identifier. Then, you |
| 40 |
communicate the identifier to the second player. When the second player joins |
| 41 |
the game, you look it up with the identifier. |
| 42 |
|
| 43 |
In addition to the game itself, you need to keep track of the WebSocket |
| 44 |
connections of the two players. Since both players receive the same events, |
| 45 |
you don't need to treat the two connections differently; you can store both |
| 46 |
in the same set. |
| 47 |
|
| 48 |
Let's sketch this in code. |
| 49 |
|
| 50 |
A module-level :class:`dict` enables lookups by identifier: |
| 51 |
|
| 52 |
.. code-block:: python |
| 53 |
|
| 54 |
JOIN = {} |
| 55 |
|
| 56 |
When the first player starts the game, initialize and store it: |
| 57 |
|
| 58 |
.. code-block:: python |
| 59 |
|
| 60 |
import secrets |
| 61 |
|
| 62 |
async def handler(websocket): |
| 63 |
... |
| 64 |
|
| 65 |
# Initialize a Connect Four game, the set of WebSocket connections |
| 66 |
# receiving moves from this game, and secret access token. |
| 67 |
game = Connect4() |
| 68 |
connected = {websocket} |
| 69 |
|
| 70 |
join_key = secrets.token_urlsafe(12) |
| 71 |
JOIN[join_key] = game, connected |
| 72 |
|
| 73 |
try: |
| 74 |
|
| 75 |
... |
| 76 |
|
| 77 |
finally: |
| 78 |
del JOIN[join_key] |
| 79 |
|
| 80 |
When the second player joins the game, look it up: |
| 81 |
|
| 82 |
.. code-block:: python |
| 83 |
|
| 84 |
async def handler(websocket): |
| 85 |
... |
| 86 |
|
| 87 |
join_key = ... # TODO |
| 88 |
|
| 89 |
# Find the Connect Four game. |
| 90 |
game, connected = JOIN[join_key] |
| 91 |
|
| 92 |
# Register to receive moves from this game. |
| 93 |
connected.add(websocket) |
| 94 |
try: |
| 95 |
|
| 96 |
... |
| 97 |
|
| 98 |
finally: |
| 99 |
connected.remove(websocket) |
| 100 |
|
| 101 |
Notice how we're carefully cleaning up global state with ``try: ... |
| 102 |
finally: ...`` blocks. Else, we could leave references to games or |
| 103 |
connections in global state, which would cause a memory leak. |
| 104 |
|
| 105 |
In both connection handlers, you have a ``game`` pointing to the same |
| 106 |
:class:`~connect4.Connect4` instance, so you can interact with the game, |
| 107 |
and a ``connected`` set of connections, so you can send game events to |
| 108 |
both players as follows: |
| 109 |
|
| 110 |
.. code-block:: python |
| 111 |
|
| 112 |
async def handler(websocket): |
| 113 |
|
| 114 |
... |
| 115 |
|
| 116 |
for connection in connected: |
| 117 |
await connection.send(json.dumps(event)) |
| 118 |
|
| 119 |
... |
| 120 |
|
| 121 |
Perhaps you spotted a major piece missing from the puzzle. How does the second |
| 122 |
player obtain ``join_key``? Let's design new events to carry this information. |
| 123 |
|
| 124 |
To start a game, the first player sends an ``"init"`` event: |
| 125 |
|
| 126 |
.. code-block:: javascript |
| 127 |
|
| 128 |
{type: "init"} |
| 129 |
|
| 130 |
The connection handler for the first player creates a game as shown above and |
| 131 |
responds with: |
| 132 |
|
| 133 |
.. code-block:: javascript |
| 134 |
|
| 135 |
{type: "init", join: "<join_key>"} |
| 136 |
|
| 137 |
With this information, the user interface of the first player can create a |
| 138 |
link to ``http://localhost:8000/?join=<join_key>``. For the sake of simplicity, |
| 139 |
we will assume that the first player shares this link with the second player |
| 140 |
outside of the application, for example via an instant messaging service. |
| 141 |
|
| 142 |
To join the game, the second player sends a different ``"init"`` event: |
| 143 |
|
| 144 |
.. code-block:: javascript |
| 145 |
|
| 146 |
{type: "init", join: "<join_key>"} |
| 147 |
|
| 148 |
The connection handler for the second player can look up the game with the |
| 149 |
join key as shown above. There is no need to respond. |
| 150 |
|
| 151 |
Let's dive into the details of implementing this design. |
| 152 |
|
| 153 |
Start a game |
| 154 |
------------ |
| 155 |
|
| 156 |
We'll start with the initialization sequence for the first player. |
| 157 |
|
| 158 |
In ``main.js``, define a function to send an initialization event when the |
| 159 |
WebSocket connection is established, which triggers an ``open`` event: |
| 160 |
|
| 161 |
.. code-block:: javascript |
| 162 |
|
| 163 |
function initGame(websocket) { |
| 164 |
websocket.addEventListener("open", () => { |
| 165 |
// Send an "init" event for the first player. |
| 166 |
const event = { type: "init" }; |
| 167 |
websocket.send(JSON.stringify(event)); |
| 168 |
}); |
| 169 |
} |
| 170 |
|
| 171 |
Update the initialization sequence to call ``initGame()``: |
| 172 |
|
| 173 |
.. literalinclude:: ../../example/tutorial/step2/main.js |
| 174 |
:language: js |
| 175 |
:start-at: window.addEventListener |
| 176 |
|
| 177 |
In ``app.py``, define a new ``handler`` coroutine — keep a copy of the |
| 178 |
previous one to reuse it later: |
| 179 |
|
| 180 |
.. code-block:: python |
| 181 |
|
| 182 |
import secrets |
| 183 |
|
| 184 |
|
| 185 |
JOIN = {} |
| 186 |
|
| 187 |
|
| 188 |
async def start(websocket): |
| 189 |
# Initialize a Connect Four game, the set of WebSocket connections |
| 190 |
# receiving moves from this game, and secret access token. |
| 191 |
game = Connect4() |
| 192 |
connected = {websocket} |
| 193 |
|
| 194 |
join_key = secrets.token_urlsafe(12) |
| 195 |
JOIN[join_key] = game, connected |
| 196 |
|
| 197 |
try: |
| 198 |
# Send the secret access token to the browser of the first player, |
| 199 |
# where it'll be used for building a "join" link. |
| 200 |
event = { |
| 201 |
"type": "init", |
| 202 |
"join": join_key, |
| 203 |
} |
| 204 |
await websocket.send(json.dumps(event)) |
| 205 |
|
| 206 |
# Temporary - for testing. |
| 207 |
print("first player started game", id(game)) |
| 208 |
async for message in websocket: |
| 209 |
print("first player sent", message) |
| 210 |
|
| 211 |
finally: |
| 212 |
del JOIN[join_key] |
| 213 |
|
| 214 |
|
| 215 |
async def handler(websocket): |
| 216 |
# Receive and parse the "init" event from the UI. |
| 217 |
message = await websocket.recv() |
| 218 |
event = json.loads(message) |
| 219 |
assert event["type"] == "init" |
| 220 |
|
| 221 |
# First player starts a new game. |
| 222 |
await start(websocket) |
| 223 |
|
| 224 |
In ``index.html``, add an ``<a>`` element to display the link to share with |
| 225 |
the other player. |
| 226 |
|
| 227 |
.. code-block:: html |
| 228 |
|
| 229 |
<body> |
| 230 |
<div class="actions"> |
| 231 |
<a class="action join" href="">Join</a> |
| 232 |
</div> |
| 233 |
<!-- ... --> |
| 234 |
</body> |
| 235 |
|
| 236 |
In ``main.js``, modify ``receiveMoves()`` to handle the ``"init"`` message and |
| 237 |
set the target of that link: |
| 238 |
|
| 239 |
.. code-block:: javascript |
| 240 |
|
| 241 |
switch (event.type) { |
| 242 |
case "init": |
| 243 |
// Create link for inviting the second player. |
| 244 |
document.querySelector(".join").href = "?join=" + event.join; |
| 245 |
break; |
| 246 |
// ... |
| 247 |
} |
| 248 |
|
| 249 |
Restart the WebSocket server and reload http://localhost:8000/ in the browser. |
| 250 |
There's a link labeled JOIN below the board with a target that looks like |
| 251 |
http://localhost:8000/?join=95ftAaU5DJVP1zvb. |
| 252 |
|
| 253 |
The server logs say ``first player started game ...``. If you click the board, |
| 254 |
you see ``"play"`` events. There is no feedback in the UI, though, because |
| 255 |
you haven't restored the game logic yet. |
| 256 |
|
| 257 |
Before we get there, let's handle links with a ``join`` query parameter. |
| 258 |
|
| 259 |
Join a game |
| 260 |
----------- |
| 261 |
|
| 262 |
We'll now update the initialization sequence to account for the second |
| 263 |
player. |
| 264 |
|
| 265 |
In ``main.js``, update ``initGame()`` to send the join key in the ``"init"`` |
| 266 |
message when it's in the URL: |
| 267 |
|
| 268 |
.. code-block:: javascript |
| 269 |
|
| 270 |
function initGame(websocket) { |
| 271 |
websocket.addEventListener("open", () => { |
| 272 |
// Send an "init" event according to who is connecting. |
| 273 |
const params = new URLSearchParams(window.location.search); |
| 274 |
let event = { type: "init" }; |
| 275 |
if (params.has("join")) { |
| 276 |
// Second player joins an existing game. |
| 277 |
event.join = params.get("join"); |
| 278 |
} else { |
| 279 |
// First player starts a new game. |
| 280 |
} |
| 281 |
websocket.send(JSON.stringify(event)); |
| 282 |
}); |
| 283 |
} |
| 284 |
|
| 285 |
In ``app.py``, update the ``handler`` coroutine to look for the join key in |
| 286 |
the ``"init"`` message, then load that game: |
| 287 |
|
| 288 |
.. code-block:: python |
| 289 |
|
| 290 |
async def error(websocket, message): |
| 291 |
event = { |
| 292 |
"type": "error", |
| 293 |
"message": message, |
| 294 |
} |
| 295 |
await websocket.send(json.dumps(event)) |
| 296 |
|
| 297 |
|
| 298 |
async def join(websocket, join_key): |
| 299 |
# Find the Connect Four game. |
| 300 |
try: |
| 301 |
game, connected = JOIN[join_key] |
| 302 |
except KeyError: |
| 303 |
await error(websocket, "Game not found.") |
| 304 |
return |
| 305 |
|
| 306 |
# Register to receive moves from this game. |
| 307 |
connected.add(websocket) |
| 308 |
try: |
| 309 |
|
| 310 |
# Temporary - for testing. |
| 311 |
print("second player joined game", id(game)) |
| 312 |
async for message in websocket: |
| 313 |
print("second player sent", message) |
| 314 |
|
| 315 |
finally: |
| 316 |
connected.remove(websocket) |
| 317 |
|
| 318 |
|
| 319 |
async def handler(websocket): |
| 320 |
# Receive and parse the "init" event from the UI. |
| 321 |
message = await websocket.recv() |
| 322 |
event = json.loads(message) |
| 323 |
assert event["type"] == "init" |
| 324 |
|
| 325 |
if "join" in event: |
| 326 |
# Second player joins an existing game. |
| 327 |
await join(websocket, event["join"]) |
| 328 |
else: |
| 329 |
# First player starts a new game. |
| 330 |
await start(websocket) |
| 331 |
|
| 332 |
Restart the WebSocket server and reload http://localhost:8000/ in the browser. |
| 333 |
|
| 334 |
Copy the link labeled JOIN and open it in another browser. You may also open |
| 335 |
it in another tab or another window of the same browser; however, that makes |
| 336 |
it a bit tricky to remember which one is the first or second player. |
| 337 |
|
| 338 |
.. admonition:: You must start a new game when you restart the server. |
| 339 |
:class: tip |
| 340 |
|
| 341 |
Since games are stored in the memory of the Python process, they're lost |
| 342 |
when you stop the server. |
| 343 |
|
| 344 |
Whenever you make changes to ``app.py``, you must restart the server, |
| 345 |
create a new game in a browser, and join it in another browser. |
| 346 |
|
| 347 |
The server logs say ``first player started game ...`` and ``second player |
| 348 |
joined game ...``. The numbers match, proving that the ``game`` local |
| 349 |
variable in both connection handlers points to same object in the memory of |
| 350 |
the Python process. |
| 351 |
|
| 352 |
Click the board in either browser. The server receives ``"play"`` events from |
| 353 |
the corresponding player. |
| 354 |
|
| 355 |
In the initialization sequence, you're routing connections to ``start()`` or |
| 356 |
``join()`` depending on the first message received by the server. This is a |
| 357 |
common pattern in servers that handle different clients. |
| 358 |
|
| 359 |
.. admonition:: Why not use different URIs for ``start()`` and ``join()``? |
| 360 |
:class: hint |
| 361 |
|
| 362 |
Instead of sending an initialization event, you could encode the join key |
| 363 |
in the WebSocket URI e.g. ``ws://localhost:8001/join/<join_key>``. The |
| 364 |
WebSocket server would parse ``websocket.path`` and route the connection, |
| 365 |
similar to how HTTP servers route requests. |
| 366 |
|
| 367 |
When you need to send sensitive data like authentication credentials to |
| 368 |
the server, sending it an event is considered more secure than encoding |
| 369 |
it in the URI because URIs end up in logs. |
| 370 |
|
| 371 |
For the purposes of this tutorial, both approaches are equivalent because |
| 372 |
the join key comes from an HTTP URL. There isn't much at risk anyway! |
| 373 |
|
| 374 |
Now you can restore the logic for playing moves and you'll have a fully |
| 375 |
functional two-player game. |
| 376 |
|
| 377 |
Add the game logic |
| 378 |
------------------ |
| 379 |
|
| 380 |
Once the initialization is done, the game is symmetrical, so you can write a |
| 381 |
single coroutine to process the moves of both players: |
| 382 |
|
| 383 |
.. code-block:: python |
| 384 |
|
| 385 |
async def play(websocket, game, player, connected): |
| 386 |
... |
| 387 |
|
| 388 |
With such a coroutine, you can replace the temporary code for testing in |
| 389 |
``start()`` by: |
| 390 |
|
| 391 |
.. code-block:: python |
| 392 |
|
| 393 |
await play(websocket, game, PLAYER1, connected) |
| 394 |
|
| 395 |
and in ``join()`` by: |
| 396 |
|
| 397 |
.. code-block:: python |
| 398 |
|
| 399 |
await play(websocket, game, PLAYER2, connected) |
| 400 |
|
| 401 |
The ``play()`` coroutine will reuse much of the code you wrote in the first |
| 402 |
part of the tutorial. |
| 403 |
|
| 404 |
Try to implement this by yourself! |
| 405 |
|
| 406 |
Keep in mind that you must restart the WebSocket server, reload the page to |
| 407 |
start a new game with the first player, copy the JOIN link, and join the game |
| 408 |
with the second player when you make changes. |
| 409 |
|
| 410 |
When ``play()`` works, you can play the game from two separate browsers, |
| 411 |
possibly running on separate computers on the same local network. |
| 412 |
|
| 413 |
A complete solution is available at the bottom of this document. |
| 414 |
|
| 415 |
Watch a game |
| 416 |
------------ |
| 417 |
|
| 418 |
Let's add one more feature: allow spectators to watch the game. |
| 419 |
|
| 420 |
The process for inviting a spectator can be the same as for inviting the |
| 421 |
second player. You will have to duplicate all the initialization logic: |
| 422 |
|
| 423 |
- declare a ``WATCH`` global variable similar to ``JOIN``; |
| 424 |
- generate a watch key when creating a game; it must be different from the |
| 425 |
join key, or else a spectator could hijack a game by tweaking the URL; |
| 426 |
- include the watch key in the ``"init"`` event sent to the first player; |
| 427 |
- generate a WATCH link in the UI with a ``watch`` query parameter; |
| 428 |
- update the ``initGame()`` function to handle such links; |
| 429 |
- update the ``handler()`` coroutine to invoke a ``watch()`` coroutine for |
| 430 |
spectators; |
| 431 |
- prevent ``sendMoves()`` from sending ``"play"`` events for spectators. |
| 432 |
|
| 433 |
Once the initialization sequence is done, watching a game is as simple as |
| 434 |
registering the WebSocket connection in the ``connected`` set in order to |
| 435 |
receive game events and doing nothing until the spectator disconnects. You |
| 436 |
can wait for a connection to terminate with |
| 437 |
:meth:`~legacy.protocol.WebSocketCommonProtocol.wait_closed`: |
| 438 |
|
| 439 |
.. code-block:: python |
| 440 |
|
| 441 |
async def watch(websocket, watch_key): |
| 442 |
|
| 443 |
... |
| 444 |
|
| 445 |
connected.add(websocket) |
| 446 |
try: |
| 447 |
await websocket.wait_closed() |
| 448 |
finally: |
| 449 |
connected.remove(websocket) |
| 450 |
|
| 451 |
The connection can terminate because the ``receiveMoves()`` function closed it |
| 452 |
explicitly after receiving a ``"win"`` event, because the spectator closed |
| 453 |
their browser, or because the network failed. |
| 454 |
|
| 455 |
Again, try to implement this by yourself. |
| 456 |
|
| 457 |
When ``watch()`` works, you can invite spectators to watch the game from other |
| 458 |
browsers, as long as they're on the same local network. |
| 459 |
|
| 460 |
As a further improvement, you may support adding spectators while a game is |
| 461 |
already in progress. This requires replaying moves that were played before |
| 462 |
the spectator was added to the ``connected`` set. Past moves are available in |
| 463 |
the :attr:`~connect4.Connect4.moves` attribute of the game. |
| 464 |
|
| 465 |
This feature is included in the solution proposed below. |
| 466 |
|
| 467 |
Broadcast |
| 468 |
--------- |
| 469 |
|
| 470 |
When you need to send a message to the two players and to all spectators, |
| 471 |
you're using this pattern: |
| 472 |
|
| 473 |
.. code-block:: python |
| 474 |
|
| 475 |
async def handler(websocket): |
| 476 |
|
| 477 |
... |
| 478 |
|
| 479 |
for connection in connected: |
| 480 |
await connection.send(json.dumps(event)) |
| 481 |
|
| 482 |
... |
| 483 |
|
| 484 |
Since this is a very common pattern in WebSocket servers, websockets provides |
| 485 |
the :func:`broadcast` helper for this purpose: |
| 486 |
|
| 487 |
.. code-block:: python |
| 488 |
|
| 489 |
async def handler(websocket): |
| 490 |
|
| 491 |
... |
| 492 |
|
| 493 |
websockets.broadcast(connected, json.dumps(event)) |
| 494 |
|
| 495 |
... |
| 496 |
|
| 497 |
Calling :func:`broadcast` once is more efficient than |
| 498 |
calling :meth:`~legacy.protocol.WebSocketCommonProtocol.send` in a loop. |
| 499 |
|
| 500 |
However, there's a subtle difference in behavior. Did you notice that there's |
| 501 |
no ``await`` in the second version? Indeed, :func:`broadcast` is a function, |
| 502 |
not a coroutine like :meth:`~legacy.protocol.WebSocketCommonProtocol.send` |
| 503 |
or :meth:`~legacy.protocol.WebSocketCommonProtocol.recv`. |
| 504 |
|
| 505 |
It's quite obvious why :meth:`~legacy.protocol.WebSocketCommonProtocol.recv` |
| 506 |
is a coroutine. When you want to receive the next message, you have to wait |
| 507 |
until the client sends it and the network transmits it. |
| 508 |
|
| 509 |
It's less obvious why :meth:`~legacy.protocol.WebSocketCommonProtocol.send` is |
| 510 |
a coroutine. If you send many messages or large messages, you could write |
| 511 |
data faster than the network can transmit it or the client can read it. Then, |
| 512 |
outgoing data will pile up in buffers, which will consume memory and may |
| 513 |
crash your application. |
| 514 |
|
| 515 |
To avoid this problem, :meth:`~legacy.protocol.WebSocketCommonProtocol.send` |
| 516 |
waits until the write buffer drains. By slowing down the application as |
| 517 |
necessary, this ensures that the server doesn't send data too quickly. This |
| 518 |
is called backpressure and it's useful for building robust systems. |
| 519 |
|
| 520 |
That said, when you're sending the same messages to many clients in a loop, |
| 521 |
applying backpressure in this way can become counterproductive. When you're |
| 522 |
broadcasting, you don't want to slow down everyone to the pace of the slowest |
| 523 |
clients; you want to drop clients that cannot keep up with the data stream. |
| 524 |
That's why :func:`broadcast` doesn't wait until write buffers drain. |
| 525 |
|
| 526 |
For our Connect Four game, there's no difference in practice: the total amount |
| 527 |
of data sent on a connection for a game of Connect Four is less than 64 KB, |
| 528 |
so the write buffer never fills up and backpressure never kicks in anyway. |
| 529 |
|
| 530 |
Summary |
| 531 |
------- |
| 532 |
|
| 533 |
In this second part of the tutorial, you learned how to: |
| 534 |
|
| 535 |
* configure a connection by exchanging initialization messages; |
| 536 |
* keep track of connections within a single server process; |
| 537 |
* wait until a client disconnects in a connection handler; |
| 538 |
* broadcast a message to many connections efficiently. |
| 539 |
|
| 540 |
You can now play a Connect Four game from separate browser, communicating over |
| 541 |
WebSocket connections with a server that synchronizes the game logic! |
| 542 |
|
| 543 |
However, the two players have to be on the same local network as the server, |
| 544 |
so the constraint of being in the same place still mostly applies. |
| 545 |
|
| 546 |
Head over to the :doc:`third part <tutorial3>` of the tutorial to deploy the |
| 547 |
game to the web and remove this constraint. |
| 548 |
|
| 549 |
Solution |
| 550 |
-------- |
| 551 |
|
| 552 |
.. literalinclude:: ../../example/tutorial/step2/app.py |
| 553 |
:caption: app.py |
| 554 |
:language: python |
| 555 |
:linenos: |
| 556 |
|
| 557 |
.. literalinclude:: ../../example/tutorial/step2/index.html |
| 558 |
:caption: index.html |
| 559 |
:language: html |
| 560 |
:linenos: |
| 561 |
|
| 562 |
.. literalinclude:: ../../example/tutorial/step2/main.js |
| 563 |
:caption: main.js |
| 564 |
:language: js |
| 565 |
:linenos: |