Learning Python Network Programming

(Sean Pound) #1
Chapter 8

A low-level event-driven chat server


So the event-driven architecture has a few great benefits, the catch is that for a
low-level implementation, we need to write our code in a completely different
style. Let's write an event-driven chat server to illustrate this.


Note that this example will not at all work on Windows as Windows lacks the poll
interface which we will be employing here. There is an older interface, called select,
which Windows does support, however it is slower and more complicated to work
with. The event-driven frameworks that we look at later do automatically switch to
select for us though, if we're running on Windows.


There is a higher performance alternative to poll called epoll, available on Linux
operating systems, however it also more complicated to use, so for simplicity we'll
stick with poll here. Again, the frameworks we discuss later automatically take
advantage of epoll if it is available.


Finally, counter-intuitively, Python's poll interface lives in a module called select,
hence we will import select in our program.


Create a file called 3.1-chat_server-poll.py and save the following code in it:


import select
import tincanchat
from types import SimpleNamespace
from collections import deque

HOST = tincanchat.HOST
PORT = tincanchat.PORT
clients = {}

def create_client(sock):
""" Return an object representing a client """
return SimpleNamespace(
sock=sock,
rest=bytes(),
send_queue=deque())

def broadcast_msg(msg):
""" Add message to all connected clients' queues """
data = tincanchat.prep_msg(msg)
for client in clients.values():
client.send_queue.append(data)
poll.register(client.sock, select.POLLOUT)
Free download pdf