Async Programming

  • #async #programming #networking
  • 204 words, Read time 1 minute, 1 second

To implement a networking layer for AirHockey, I'll need async programming, since a game server spends most of its life waiting: waiting for a message, waiting for the next paddle update, waiting for a player who wandered off.

The naive approach is to handle one thing, finish it, then move to the next. That falls apart the moment two people are playing, because while you sit blocked waiting on one player's packet, the other player's puck freezes.

Async fixes this with the event loop, just like a single very caffeinated waiter running the whole restaurant. The waiter takes an order, and instead of standing at the table until the kitchen is done, it moves on to serve everyone else, circling back only when something is actually ready. Nobody gets their own waiter, yet nobody waits long.

async and await are how you talk to that waiter. Marking a function async means it can pause partway through, and await is "I am waiting on something slow, go help someone else." The event loop parks that task and picks up whatever is ready to run.

For WebSockets juggling many open connections at once, this is exactly what AirHockey wants: one loop, many conversations, nobody blocking anybody.