Netpong honors one the very first computer games, Table Tennis for Two, and the later Atari implementation of Pong. My version of Netpong is coded using only system calls and TCP, and paints the screen by using the ncurses library.
The trick to netpong is to coordinate state, and to sync server and client via TCP. In addition, the program must remain responsive and not use much CPU. In my case, I achieve this restrictions by using the ‘select’ call, which allows for light-weight non-blocking IO. Select is part of the magic behind NGINX for example.
To implement non-blocking i/o on standard input, so that the user can move the paddle up and down, or quit if desired, I use select() to block/sleep, and to watch for the socket and standard input. When the listening socket is ‘readable’ we are ready to accept() TCP incoming messages. This also allows for a responsive application when the handshake takes a while.
When playing, both the server and client use select() to attend to keyboard input (to move the paddle, or to quit)I also use select() to read when data is ready. To write I first check to see if a write is pending. If it is, select is enabled to check for write availability on the network.
The code for netpong, the apex project to Harvard’s Unix Systems Programming class, can be found in github here or click on the Octocat on the left. The code has been tested in Mac & Ubuntu and is compiled using gcc -Wall (Makefile included @ github). Enjoy tennis playing!!!