Running the Client/Server Demo
To run the client/server demo programs, you need to have two separate command-line sessions open.
You can do that in your LXDE graphical desktop by opening two separate LXTerminal windows.
In one window, you start the script2003.py server program first:
Click here to view code image
pi@raspberrypi ~ $ python3 script2003.py
Listening for a client...
When you see the message that the server is listening for a client, you can start the
script2004.py client program in the other LXTerminal window:
Click here to view code image
pi@raspberrypi ~ $ python3 script2004.py
Welcome to my server!
Enter text to send:this is a test
If all goes well, you see the welcome message sent from the server, along with a prompt for the text to
send back. Enter a short message and press Enter.
When you send the message from the client, you should see it appear in the server window:
Click here to view code image
Accepted connection from: ('127.0.0.1', 46043)
Received data from client: this is a test
The client window should receive the response back from the server:
Click here to view code image
Received from server: this is a test
Enter text to send:
When you enter the word exit at the client prompt, both the server and client connections terminate
and stop the programs.
Congratulations! You’ve just written a complete Python client/server application!
Watch Out!: Closing Sockets
If you try to restart the script2003.py server program immediately after it closes,
you may get an error message that the socket is still in use. By default, Linux systems
allow socket connections to linger open for a while after they’ve been closed, in case
any stray network data comes across. The socket usually fully closes and is ready for
reuse within a minute or so. You can monitor this by using the netstat –t
command. You should see a connection for TCP port 5150 in a TIME_WAIT status
while the system is waiting to close the socket.
Summary
In this hour, you explored the world of network programming with Python scripts. You learned about
the various modules available that allow your Python scripts to interact with a myriad of network
servers. You got to see two specific examples: using Python to send email messages and using Python