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

(singke) #1

same time, they’ll deadlock, and nothing will happen. Likewise, if they both attempt to send a
message at the same time, nothing will be accomplished. It’s your job as the network programmer to
decide what protocol rules your client and server programs must follow in order to communicate.


You create client/server programs by using sockets. Sockets are the interface between your program
and the physical network connection on the client and server devices. Creating the code to interact
with the network connection is called socket programming.


The Python socket Module


Python includes the socket module in the standard Python libraries to help you write network
programs. This module provides all the methods you need for both the server and client sides of the
connection. Table 20.3 shows the methods you use to write network programs.


TABLE 20.3 Python socket Module Methods

There are also lots of methods for converting host addresses into different formats used on the
Internet. This hour doesn’t dig into all those details, as you don’t need them for the simple scripts
you’ll create. If you’re interested in them, though, check out the socket module documentation on
the docs.python.org website for more information.


Creating the Server Program


To demonstrate the creation of a client/server program using Python, you’re going to set up a simple
network application. The server program you’ll create will listen for incoming connection requests
on TCP port 5150. When a connection request comes in, the server will accept it and then send a
welcome message to the client.


The server program will then wait to receive a message from the client. If it receives a message, the
server will display that message and then send the same message back to the client. After sending the
message, the server will loop back to listen for another message. This loop will continue until the
server receives a message that consists of the word exit. When that happens, the server will
terminate the session.


To create the server program, you use the socket module to create a socket and listen for incoming
connections on TCP port 5150, as shown in this example:

Free download pdf