Learning Python Network Programming

(Sean Pound) #1

Client and Server Applications


Because we're only running in a single thread, we don't need any of the
synchronization mechanisms which we had to employ in the multithreaded server.
We're just using a regular dict to keep track of our clients. If you've not come across
it before, the SimpleNamespace object that we use in the create_client() function
is just a new idiom for creating an empty object with a dict (this is needed
because Object instances don't have a dict so they won't accept arbitrary
attributes). Previously, we may have used the following to give us an object which
we can assign arbitrary attributes to:


class Client:
pass
client = Client()

Python version 3.3 and later versions give us the new, more explicit
SimpleNamespace object.


We can run our multithreaded client against this server. The server is still using the
same network protocol, and the architecture of the two programs won't affect the
communication. Give it a try and verify if it works as expected.


This style of programming, employing poll and non-blocking sockets, is often
referred to as non-blocking and asynchronous, since we use sockets in non-blocking
mode, and the thread of control handles I/O reactively, as it needs to happen, rather
than locking to a single I/O channel until it's done. However, you should note that
our program isn't completely non-blocking, since it still blocks on the poll.poll()
call. This is pretty much inevitable in an I/O bound system because when nothing's
happening, you've got to wait for the I/O activity somewhere.


Frameworks


As you can see, writing servers using these lower level threading and poll APIs
can be quite involved, especially considering that various things which would be
expected in a production system, such as logging and comprehensive error handling,
haven't been included in our examples due to brevity.


Many people have hit these problems before us, and several libraries and
frameworks are available for taking some of the leg work out of writing the
network servers.

Free download pdf