← All work
2024C#MonoGameNetworkingTCP/UDPMultithreading

Tanks

An online multiplayer tank battling game for up to four players who have to bounce bullets off the walls of randomly generated mazes. The networking is built from raw sockets and includes a multithreaded lobby server with matchmaking, rooms, TCP + UDP traffic, spectating and chat.

Duration
2 months
Platform
PC
Module Grade
94%
Tanks

Tanks is an online multiplayer game for up to four players, built in C# with MonoGame for a second-year multiplayer programming module. Players fight across randomly generated mazes, bouncing shells off the walls to hit each other, and the first player or team to win four rounds takes the game.

I wrote the whole networking layer from scratch on top of raw sockets. It includes a lobby server with matchmaking, rooms that each run their own game, a mix of TCP and UDP traffic, spectating and in-game chat.

A four player free-for-all round with bots. Video is sped up 2.5x
  • 4 game modes, from 1v1 duels to 2v2 teams
  • 19 packet types in a shared packet library
  • TCP + UDP reliable game events, plus fast aim updates
  • 1 server hosting any number of rooms at once

Architecture

The solution has three projects: the game client, a dedicated server, and a packet library that the other projects reference, so the client and server always agree on the data being sent.

The server has two layers:

Threading

Every connected client gets its own thread doing blocking reads. Each room then has two more threads: one runs the game loop (countdowns, the round timer, scoring), and one works through a queue of incoming player requests. Client threads never touch room state directly. They push a request onto a ConcurrentQueue, and the room’s request thread runs them one at a time:

Server/Room.cs
private void OnClientRecievedPacket(ConnectedClient client, Packet packet)
{
    switch (packet.Type)
    {
        case PacketType.SYNC_INPUT:
            m_RequestQueue.Enqueue(() => { OnSyncInputPacket(client, (SyncInputPacket)packet); });
            break;
        case PacketType.HIT_PLAYER:
            m_RequestQueue.Enqueue(() => { OnHitPlayerPacket(client, (HitPlayerPacket)packet); });
            break;
        // ...
    }
}

Joining a room is the one place where two client threads can race, for example two players accepting the last slot at the same moment. That is guarded with a lock, and the room starts its game threads as soon as it’s full.

The client does the same thing in reverse. Its network threads only queue packets, and the game flushes the queue once per frame on the main thread, so game objects are never changed in the middle of an update.

Packets

Packets are C# classes serialised to JSON. Over TCP they’re sent one per line, so the reader just calls ReadLine(). Every packet carries a Type, and a custom JsonConverter reads that field first to decide which class to deserialise into. Adding a new packet only needs a class and one line in the converter.

Packet Library/Packets.cs
var root = doc.RootElement;
if (root.TryGetProperty("Type", out var typeProperty))
{
    return (PacketType)typeProperty.GetByte() switch
    {
        PacketType.START_ROUND => JsonSerializer.Deserialize<StartRoundPacket>(root.GetRawText(), options),
        PacketType.SYNC_INPUT  => JsonSerializer.Deserialize<SyncInputPacket>(root.GetRawText(), options),
        PacketType.HIT_PLAYER  => JsonSerializer.Deserialize<HitPlayerPacket>(root.GetRawText(), options),
        // ...one line per packet type
        _ => throw new NotImplementedException()
    };
}
All 19 packet types
Stage Packets
Connecting CLIENT_ID, LINK_UDP, SET_USERNAME
Lobby START_MATCHMAKING, LEAVE_MATCHMAKING, MATCH_FOUND, JOIN_ROOM, GET_ROOMS
Round flow START_ROUND, UPDATE_TIMER, END_ROUND, END_GAME, LEAVE_ROOM
Gameplay SYNC_INPUT, SYNC_TRANSFORM, SYNC_BARREL, PROJECTILE_SYNC, HIT_PLAYER
Social CHAT_MESSAGE

TCP and UDP

Most traffic goes over TCP, because it has to arrive and arrive in order. A missed “round started” or “player hit” would leave a client out of step with everyone else.

Barrel aim is different. Every player’s turret follows their mouse, so it changes almost every frame, and only the latest angle matters. Barrel rotation is sent over UDP every frame. The packet is marked ShouldReplace, so the client keeps only the newest one of that type and throws away older ones still waiting in the queue:

Client/NetworkManager.cs
m_UDPRequestQueue.AddOrUpdate(packet.Type,
    (key) => new Queue<UDPPacket>(new[] { packet }),
    (key, data) =>
    {
        if (packet.ShouldReplace)
        {
            data.Clear(); // only the newest one matters
        }

        data.Enqueue(packet);
        return data;
    });

UDP packets don’t come with a connection, so the server needs to know which client sent each one. When a client connects, it receives its ID over TCP and replies with a LINK_UDP packet containing its UDP address. The server stores that address against the client and uses it to match up incoming datagrams.

Movement

Rather than sending positions every frame, each client only sends its input, and only when it changes:

Client/TankControl.cs
if (input != m_PreviousInput)
{
    NetworkManager.m_Instance.TCPSendPacket(new SyncInputPacket((int)input.X, (int)input.Y));
    m_PreviousInput = input;
}

if (m_TimeSinceLastSync > 2)
{
    m_TimeSinceLastSync = 0;
    NetworkManager.m_Instance.TCPSendPacket(new SyncTransformPacket(m_Rigidbody.m_Body.Position.X, m_Rigidbody.m_Body.Position.Y, m_Rigidbody.m_Body.Rotation));
}

Your own tank moves straight away on your machine. Every other client runs the same movement code with the last input it received for you, so a tank holding W for three seconds costs two packets (key down and key up) instead of hundreds of position updates.

Two copies running the same input will still drift apart over time, because of frame timing and collisions. So every two seconds the owner also sends its real position and rotation, and the other clients snap to it.

Playing with a simulated lag of 100ms

Shooting

When a player fires, their client spawns the shell and sends a PROJECTILE_SYNC packet with the shell’s ID, position and angle. Everyone else spawns a matching copy. Shells bounce by reflecting their velocity off the wall’s contact normal:

Client/ProjectileMovement.cs
contact.GetWorldManifold(out Vector2 normal, out _);

Vector2 velocity = m_RigidBody.m_Body.LinearVelocity;
Vector2 reflectedVelocity = velocity - 2 * Vector2.Dot(velocity, normal) * normal;
A bullet ricocheting of some walls

Hits are decided by the shooter’s client. Only the original copy of a shell checks for hits. When it hits a tank, the shooter reports HIT_PLAYER, and the server marks that player dead and passes the hit on to everyone. The benefit is that when you hit something it always counts, however this means the server always trusts the client.

Rounds and maps

Each room’s game loop runs the match where it starts a round, begins a 2-minute timer, ends the round when one team is left, updates the scores, and repeats until someone reaches four wins.

Maps are mazes generated with randomised Prim’s algorithm. The server never sends the map itself. It sends a single seed in the START_ROUND packet, and every client generates the same maze from that seed. The server uses the same seed to pick spawn points, so it knows they’re inside the maze without ever building it.

The round countdown is also synchronised. START_ROUND includes the exact time the round begins, three seconds in the future, so every client’s initial countdown finishes together no matter when the packet arrived.

Matchmaking and rooms

The four game modes
The four game modes

Game modes

Duels, 3-player free-for-all, 4-player free-for-all, and 2v2 teams. Teams are balanced as players join by putting each new player on the team with the fewest players.

Players pick a mode and join a queue. When there are enough players waiting for that mode, the server creates a room with a unique six-character code, sends each matched player a MATCH_FOUND packet with it, and they join the room using that code.

Spectating

The spectate menu lists every game in progress. Joining a running room adds you as a spectator. You wait for the next round to start, then receive exactly the same round data as the players. The server ignores any gameplay packets sent by spectators, so a modified client can’t use spectator mode to interfere with a match.

Chat

The in-game chat
Players and a spectator chatting

Chat

Players and spectators can chat during a match. The server formats each message before sending it on, so names show up in their team colour and spectators are tagged and shown in grey. The server also posts round results and disconnects into the chat, and the chat history carries over between rounds.

Looking back

This was my first time writing networking code from scratch, and there are things I’d do differently now:

UML class diagram

UML Class Diagram
Class diagram of the server
SDF Modelling Engine →Next project