Writing a simple TCP echo client/server application
After testing with basic socket APIs in Python, let us create a TCP socket server and client now. Here, you will have the chance to utilize your basic knowledge gained in the previous recipes.
How to do it...
In this example, a server will echo whatever it receives from the client. We will use the Python argparse
module to specify the TCP port from a command line. Both the server and client script will take this argument.
First, we create the server. We start by creating a TCP socket object. Then, we set the reuse address so that we can run the server as many times as we need. We bind the socket to the given port on our local machine. In the listening stage, we make sure we listen to multiple clients in a queue using the backlog argument to the listen()
method. Finally, we wait for the client to be connected and send some data to the server. When the data is received, the server echoes back the data to the client.
Listing 1.13a shows how to...