Skip to main content

Tutorial 2: A Simple TCP Server

Source

The first practical network program is a TCP server that accepts one connection and exchanges simple text. It can be tested from another computer with telnet or nc.

Server flow

A TCP server normally performs these steps:

  • open a socket
  • bind the socket to a local port
  • put the socket into listening mode
  • accept an incoming connection
  • send and receive data on the accepted socket
  • close the accepted socket when finished

The original listening socket remains available for future connections; the accepted socket is the one used for the actual data transfer.

Opening the socket

In assembly, a TCP socket is opened by passing SOCK_STREAM and calling the SOCKET routine through HLCALL:

ld c, SOCK_STREAM
ld hl, SOCKET
call HLCALL
jr c, .error
ld (v_sockfd), a

In C, the same operation is:

int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);

Errors are reported with carry set in assembly, or with a negative return value in C.

Binding and listening

The server binds the socket to the port it wants to receive connections on, then calls listen. In the tutorial example, port 2000 is used so a PC can connect with:

telnet 172.16.0.38 2000

After accept returns, the program sends a greeting, reads text sent by the remote side, and exits when the input begins with x.

Closing sockets

Sockets are limited hardware resources. Programs should close accepted sockets and listening sockets when finished. Reset clears socket state, but programs should not rely on reset as normal cleanup.