STR Coding Club logo STR Coding ClubLearn to code, together
Games

How Beginner Coders Keep an Online Game Connection Stable With Retry Logic

The first networked game most club members build works perfectly on the club's own Wi-Fi. Two laptops, one simple server, two players moving dots around a shared screen.

Illustration of a signal wave breaking and reconnecting between two laptops

The first networked game most club members build works perfectly on the club's own Wi-Fi. Two laptops, one simple server, two players moving dots around a shared screen. Then someone takes a laptop home, connects over a phone hotspot, walks into the kitchen, and the game freezes forever. No error, no message, just a frozen dot.

Players feel this problem long before coders understand it. Anyone who plays online knows the difference between a game that recovers from a hiccup and one that throws you to the menu. A club member who plays a lot of mobile games keeps a running note of which apps and sites stay usable on a shaky train connection, a list that includes two rhythm games, a chat app, a game wiki and ankertoto, and she noticed the ones that cope well all behave in similar ways. They notice when the connection drops, they try again sensibly, and they tell you what is happening. In this project we build exactly those three behaviours into a small Python client.

Version One: The Naive Client

The starting point is the client most beginners write. It opens a socket to the server, then loops forever: send the player's position, wait for the other player's position, draw both.

This works when the network is perfect. It fails in three ways when it is not:

  • If the server is not reachable at start up, the program crashes with a connection refused error.
  • If the connection drops mid game, the wait for data never returns, and the game freezes.
  • If data arrives late, the game stutters because drawing waits for the network.

Members run the naive version and deliberately break it: they stop the server, or turn off Wi-Fi for five seconds. Seeing the freeze happen on purpose is far more instructive than reading about it.

Version Two: Timeouts and Detection

The first fix is to stop waiting forever. Python sockets accept a timeout, set with settimeout(2.0), so that a receive call gives up after two seconds and raises an exception instead of hanging.

Members wrap the receive in a try and except block. If a timeout happens once, the client keeps the last known position of the other player and carries on. If timeouts happen three times in a row, the client decides the connection is lost and shows a "Reconnecting" message on screen.

This is also where we introduce a heartbeat. Every second, the client sends a tiny "still here" message even if the player has not moved. The server does the same. Without heartbeats, a player standing still looks identical to a player who has disconnected.

Version Three: Retrying Without Making Things Worse

Once the client knows the connection is lost, it needs to reconnect. The beginner instinct is a tight loop that tries again immediately, forever. That is a bad idea. If the server is down and twenty clients are all retrying hundreds of times a second, they can keep it down when it tries to come back.

The standard approach is exponential backoff. The client waits a little, tries, and if that fails, waits twice as long before the next try, up to a maximum. Here is the schedule we use:

AttemptWait before trying
10.5 seconds
21 second
32 seconds
44 seconds
5 and later8 seconds, plus a random extra of up to 1 second

The random extra, called jitter, stops all the clients from retrying at precisely the same instant. Members implement this as a small function that takes the attempt number and returns a delay, which is a neat exercise in itself: powers of two, a minimum function for the cap, and random.uniform for the jitter.

Version Four: Keeping the Game Smooth

Even with reconnection, the game still stutters if drawing waits on the network. The fix is to separate the two jobs. The network code runs in its own thread, receiving updates and storing the latest position in a shared variable. The game loop reads that variable and draws at a steady 30 frames per second, whether or not new data has arrived.

Threads are a big topic for beginners, so we keep it minimal: one background thread, one shared dictionary, and a lock around reads and writes. For members not ready for threads, a non-blocking socket checked once per frame achieves a similar result with less theory.

Telling the Player What Is Happening

The last piece is communication. A frozen screen is frustrating. A screen that says "Connection lost, retrying in 4 seconds (attempt 3)" is reassuring. Members add a small status line at the top of the window with three states: connected, reconnecting with a countdown, and offline with a button to try again manually.

This is a user interface lesson as much as a networking one, and it ties in nicely with our earlier project on game menus as first interface projects.

The Advice We Disagree With

Beginners often read that "TCP is reliable, so you do not need to handle lost data." That is half true. TCP will retransmit lost packets, so data that arrives is complete and in order. But TCP cannot make a dead connection alive, and it can take a very long time, sometimes minutes, to notice that a connection has died. That is why the naive client freezes. Reliable delivery is not the same as a stable connection, and your code has to handle the gap.

Testing It Properly

We finish with a testing session. Members try each of these and note what their client does:

  1. Start the client before the server is running.
  2. Stop the server mid game for 10 seconds, then restart it.
  3. Turn off Wi-Fi for 3 seconds, then for 30 seconds.
  4. Run the server on a laptop and walk it to the edge of Wi-Fi range.

Each failure becomes a debugging task. Members who enjoyed learning to debug patiently through game bugs tend to love this part. Those curious about what happens on the wire can continue with how gaming servers explain networking basics.

By the end, the dot that used to freeze in the kitchen now pauses, shows a message, and comes back on its own. That small change is what players mean when they say a game feels stable.

IA
Imogen Achebe

Imogen started a coding club at her school and now trains volunteer mentors. She writes about first steps in coding and projects that work for groups of mixed ability.

More posts by Imogen

More in Games

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto