Learning Python Network Programming

(Sean Pound) #1

Client and Server Applications


Client and server


The basic setup in the client/server model is one device, the server that runs a
service and patiently waits for clients to connect and make requests to the service.
A 24-hour grocery shop may be a real world analogy. The shop waits for customers
to come in and when they do, they request certain products, purchase them and
leave. The shop might advertise itself so people know where to find it, but the actual
transactions happen while the customers are visiting the shop.


A typical computing example is a web server. The server listens on a TCP port for
clients that need its web pages. When a client, for example a web browser, requires
a web page that the server hosts, it connects to the server and then makes a request
for that page. The server replies with the content of the page and then the client
disconnects. The server advertises itself by having a hostname, which the clients
can use to discover the IP address so that they can connect to it.


In both of these situations, it is the client that initiates any interaction – the server is
purely responsive to that interaction. So, the needs of the programs that run on the
client and server are quite different.


Client programs are typically oriented towards the interface between the user and
the service. They retrieve and display the service, and allow the user to interact
with it. Server programs are written to stay running for indefinite periods of time,
to be stable, to efficiently deliver the service to the clients that are requesting it, and
to potentially handle a large number of simultaneous connections with a minimal
impact on the experience of any one client.


In this chapter, we will look at this model by writing a simple echo server and client,
and then upgrading it to a chat server, which can handle a session with multiple
clients. The socket module in Python perfectly suits this task.


An echo protocol


Before we write our first client and server programs, we need to decide how
they are going to interact with each other, that is we need to design a protocol
for their communication.

Free download pdf