Learning Python Network Programming

(Sean Pound) #1
Chapter 8
eventlet.spawn_n(handle_client_send,
client_sock,
q,
addr)
print('Connection from {}'.format(addr))

We can test this with our multithreaded client to ensure that it works as expected.


As you can see, it's pretty much identical to our multithreaded server, with a few
changes made so as to use eventlet. Notice that we've removed the synchronization
code and the lock around send_queues. We're still using queues, although they're
the eventlet library's queues, because we want to retain the blocking behavior of
Queue.get().


There are more examples of using eventlet for programming on the
eventlet site at http://eventlet.net/doc/examples.html.

An asyncio-based chat server


The asyncio Standard Library module is new in Python 3.4 and it is an effort at
bringing some standardization around asynchronous I/O into the Standard Library.
The asyncio library uses a co-routine based style of programming. It provides a
powerful loop class, which our programs can submit prepared tasks, called
co-routines, to, for asynchronous execution. The event loop handles the scheduling
of the tasks and optimization of performance around blocking I/O calls.


It has built-in support for socket-based networking, which makes building a basic
server a straightforward task. Let's see how this can be done. Create a new file called
5.1-chat_server-asyncio.py and save the following code in it:


import asyncio
import tincanchat

HOST = tincanchat.HOST
PORT = tincanchat.PORT
clients = []

class ChatServerProtocol(asyncio.Protocol):
""" Each instance of class represents a client and the socket
connection to it. """
Free download pdf