Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Linking Programs Using Socket Programming


Besides connecting to other servers, Python also allows you to create your own servers on a network.
You can write a server application that listens for connections from client programs and
communicates with the client programs across the network, allowing you to move your application
around the network.


In the following sections, you’ll first learn how the client/server paradigm works in network
programming, and then you’ll see how to create your own server and client programs by using Python
scripts.


What Is Socket Programming?


Before diving into client/server programming, it’s a good idea to have an understanding of how client
and server programs operate. Obviously, the client program and the server program each have
different responsibilities in the connection and transfer of data.


A server program listens to the network for requests coming from clients. A client program initiates a
request to the server for a connection. Once the server accepts the connection request, a two-way
communication channel is available for each device to send and receive data. Figure 20.3 shows this
process.


FIGURE 20.3 The client/server communication process.

As you can see in Figure 20.3, the server must perform two functions before it can communicate with
the client. First, it must set up a specific TCP port to listen for incoming requests. When a connection
request comes in, it must then accept the connection.


The client’s responsibility is much simpler. All it must do is attempt to connect to the server on the
specific TCP port on which the server is listening. If the server accepts the connection, the two-way
communication is available, and the data can be sent.


Once a connection is established between the server and the client, the two devices must use some
sort of communication process (or protocol). If both devices attempt to listen for a message at the

Free download pdf