Skip to content

Chapter 4 ‐ Starting to serve

Sebastian Steinhauer edited this page Sep 11, 2023 · 2 revisions

Abstract

In this chapter we are going to implement the first server code.

Background

Before we start implementing the server, we have to talk about computer networking a bit. I will not and cannot give you a complete in depth overview of the pros / cons of various network implementations, but I try to enlighten you a little.

IP

When you start reading about networking you soon will stumble across terms like IP, TCP and UDP. To put it simply IPv4/IPv6 means how the computers will be addressed in the network/internet. The good old IPv4 is always something like 192.168.2.1 or similar. It is divided into 4 octets ranging from 0 - 255. So the theoretical lowest address is 0.0.0.0 and the highest possible address would be 255.255.255.255. But there are a lot of addresses with special meanings. In IPv6 the address space got enhanced and addresses look like 2001:db8::8a2e:370:7334. You can think of real house addresses here. On top of the IP (internet protocol) sit many transport layer protocols with various capabilities. As a normal user application an operating system gives you access to TCP and UDP.

TCP

The Transmission Control Protocol (TCP) represents a connection between a client and server and is presented as an endless data stream to the programmer. Like a indefinitely large file where you can read from and write to. Everything you write to this TCP connection on one end will be received exactly as it is on the remote end. It is a very reliable protocol and a lot of applications like your web browser are using it. Even popular MMO-RPGs like World of Warcraft use TCP/IP internally.

  • reliable connection between client / server
  • connection is represented as an endless stream of data
  • disconnects / traffic congestion is handled by the operating system
  • data will be received exactly as you have sent it

UDP

The User Datagram Protocol (UDP) is much simpler. There is no connection between client and server, but just individual packets you can send from one computer to another. There is no guarantee that those packets will arrive at their destination or arrive in the order you have sent them. It's like a shotgun where you aim at a remote host, fire and hope that some packets will arrive.

  • no idea of a connection
  • you have to send individual packets of small size (it's recommended to use size < 512 bytes)
  • no guarantee that they will arrive in order or at all

TCP/UDP

So when you compare the feature set of both transport protocols it's obvious which you should use, right? Wrong!! In order to give you the illusion of an endless, reliable stream of data the operating system and it's TCP/IP implementation have to go great lengths in order to achieve this. In fact the internet is more like UDP. Computers send small packets across the line and hope for the best. For a quick real time game like shooters, TCP is simply not "fast" enough for proper gameplay. The reason lies in the implementation of TCP. The operating system has to cache TCP packets, reorder them as needed and ask for retransmission of one of the packets got lost. So the OS is the gatekeeper for your data, and even if newer packets are received the OS won't give them to you, because the older ones are still missing. This effect is called head of line blocking. And there are even other mechanics in TCP which make it unsuitable for gaming. We are going to send our button state in one byte. But the TCP header is so big, that the operating system will likely cache our input bytes until a reasonable size has been accumulated and then send them across the internet (Nagle's Algorithm). So the server might receive no inputs for quite some time and then a whole lot at once.

This means UDP is for games often the better option here. In our case we could live with TCP limitations as our game is probably not as fast as Quake or Unreal Tournament, but I'm going to use UDP as well, because it makes my life easier as you will see.

Fat Client

Most games are so called "fat clients". This means the client has a very complete image of the game it is actually playing. In terms of an MMO-RPG, the client knows that there are players, monsters, items, an inventory system and a huge world. Server and client actually talk in very brief packets what is happening. For example "Monster X, is of type Y and moving to 10, 20" or "Player is attacking monster X" etc. You can see it like letter chess where you simply exchange commands like "pawn from D2 to D3" and everyone knows exactly what is meant.

Thin Client

A thing client is the whole opposite of a fat client. A thin client normally doesn't even know what kind of application it shows to the user. You can think of a simple terminal where you can login to a remote computer and start an editor, chat program or a simple game like rogue or nethack. In more modern terms you can also compare a web browser to a thin client (even though web browsers are one of most complex software today). A web browser doesn't know if its Facebook, ebay or Spotify. It simply shows what the server tells the browser to show. And inputs are sent verbatim to the server. So every keypress, mouse click etc. has no meaning to the thin client but is only sent to the server, which knows how to interpret this. In terms of our letter chess, its more like you send a picture of the whole chess board every time something has changed.

Fat vs Thin Client

As you might imagine, sending a whole picture every time from server to client requires more processing power on the server side and also uses much much more traffic, than specific instructions like "pawn from D2 to D3". On the other hand, if you have a thin client, you can easily add new game mechanics or interface to you game as the client simply displays what the server sends. In our little project we are going to use the thin client approach as it will help us focusing on the interesting parts of the game and not implementing a complex network protocol. Just think of all the possible actions a player could to in your world and then add the monsters, items and NPCs. You quickly reach 100 commands you have to implement both on the server and the client side. Boring!

Design Decisions

As we have implemented a very simple tile based renderer in the first chapter, we are going to utilize this in our thin client approach. Remember, the whole 128x128 pixel screen can be represented by 16x16 8-bit values which will result in 256 bytes. This is super tiny. If the server is just sending this 256 bytes 20 times per second to the client, we have 5KiB/s or 40kbit/s which we have to transfer. Just check your internet connection, it has probably multiple mbit/s so there is plenty room (even a YouTube video will need more bandwidth).

So we can simply send 256 bytes every frame from server to client and the client will simply send a byte 20 times per second representing its button states. But remember, it is UDP we are talking about. Packets can arrive not at all or out of order. We can simply "fix" this problem by adding a counter to the packet, which will increase for every packet. When the server receives a packet with a lower counter it will simply reject the packet, as a packet with newer information was already received (this eliminated the head of line blocking problem). But what about missing packets? We simply don't care. As server and client are sending 20 times per second an update, we can simply ignore missing packets as a new one will soon arrive anyways.

Okay. But what about sound? This is also easy. Add another 32-bit (4 bytes) to each packet which is sent from the server. And every bit represents one of the 32 sound effects which should be played. This means that a sound effect could go missing when the network is unstable, but this is neglectable. Music is just adding another byte which sets the music number to play. Done.

This gives us an extremely simple network protocol which only has two different packet types. One is sent from server to client, one is sent from client to server.

Client to server packet (5 bytes):

Position Size Description
0 4 32-bit counter
4 1 8-bit input mask

Server to client packet (265 bytes):

Position Size Description
0 4 32-bit counter
4 4 32-bit sound effect mask
8 1 8-bit music ID
9 256 16x16 tile screen content

Implementation

Unix / Windows

Networking is unfortunately one of the things which are not standardized in the C library. In fact you have to use operating system calls to do networking. As we don't want to include any dependencies we have to implement the server with those operating system calls. As most servers nowadays run Linux (and I'm developing this on a Mac) the server code will only run on Unix systems. It should be very easy to port it to Windows systems but I don't have the patience to do it right now.

Connections with UDP

When UDP has no connection, how you can implement one? Very simple. The server reads every UDP packet it will receive and search in an internal list of clients the appropiate client which IP address matches. If no client was found, a new client with that address is created. The server also keeps track when the last "valid" packet was received from the client. If for a certain amount of time no other packet was received this client will be simply reset (disconnected) and can be reused for another connection. Oh ... this is also one small benefit of UDP here. We only need one UDP socket for thousands of clients as the mapping of the client is done in our program instead of the operating system (TCP would create a new socket for every connection).

Creating an UDP socket

Look at this. This is all we need to create an IPv4 UDP socket. The last fcntlcall will cause the socket to be non blocking. This means when we try to receive a packet from this socket and there is no packet, it will return with 0 and we can continue.

    // open UDP server socket
    if ((state.net.udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
        panic("socket() failed: %s", strerror(errno));
    struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(NETWORK_PORT), .sin_addr.s_addr = INADDR_ANY };
    if (bind(state.net.udp, (const struct sockaddr*)&addr, sizeof(addr)))
        panic("bind() failed: %s", strerror(errno));
    if (fcntl(state.net.udp, F_SETFL, O_NONBLOCK, 1))
        panic("fcntl() failed: %s", strerror(errno));

Receiving data

Most work is actually done in this function.

// receive UDP packets
static void receive_packets(void) {
    for (;;) {
        // receive next UDP packet if available
        uint8_t data[1024];
        struct sockaddr_in addr = {0};
        socklen_t addr_len = sizeof(addr);
        int received = recvfrom(state.net.udp, data, sizeof(data), 0, (struct sockaddr*)&addr, &addr_len);
        if (received <= 0) return;
        if (received < 5) continue;
        // find client for this packet
        client_t *client = create_client(addr);
        if (client == NULL) continue;
        // handle the client and receive the input
        const uint32_t tick = read_uint32(&data[0]);
        if (tick <= client->net.recv_tick) continue;
        client->net.last_tick = state.tick;
        client->net.recv_tick = tick;
        client->input.pressed = (~client->input.down) & data[4];
        client->input.down = data[4];
    }
}

As you can see, we start an endless loop receiving packets from the UDP socket. If 0 or less bytes are received, there is no packet left, so we can quit the function. If the received packet has not the size of 5 bytes, we ignore it and try to receive the next one. Then we try to find the client in our array and quit if no client can be allocated. Now comes the counter code which is also simple. Decode the first 4 bytes of the packet as a big-endian 32-bit integer. Check if this tick is greater than what we already received. If this is the case, we just set the current server tick as the last tick we received data. Save also the received tick as the last received tick in the client. The last 2 lines will simply update the pressed 8-bit structure with buttons which were "just" pressed in this frame and save also all buttons which are down.

Clone this wiki locally