Simple TCP/IP echo server

This program demonstrates a simple TCP/IP server. It will accept a connection from a client application, receive one line of text, echo that line back to the client and close the connection.

Programming Issues

This program illustrates the classic process for a TCP/IP server program. Summarised, it is as follows:

Note that it's present form, the server enters an infinite loop and has no mechanism for closing itself. We have to use a command such as kill to terminate it.


Once launched in the background, the server can be used either with a dedicated echo client, or simply by telnetting to it. For the latter approach, the following is a sample session using Linux:

[paul@localhost paul]$ ./echoserv 3357 &
[paul@localhost paul]$ telnet localhost 3357
Connected to localhost.
Escape character is '^]'.
Echo this line for me, please.
Echo this line for me, please.
Connection closed by foreign host.
[paul@localhost paul]$

After executing telnet and receiving some initialisation output, we enter the words "Echo this line for me, please.", and we see the server process echoing them back to us, then closing the connection.

You can specify the port number to listen to as a command line argument. The program will default to ECHO_PORT (#defined as 2002) if one is not supplied.

Source and Downloads