Using asyncio in event-driven network library

Tobias M. tm at
Mon Dec 23 12:50:29 CET 2013


I am currently writing an event-driven client library for a network 
protocol [1] and chose to use the new asyncio module. I have no 
experience with asynchronous IO and don't understand all the concepts in 
asyncio yet. So I'm not sure if asyncio is actually the right choice .

My goal:
I want to provide an easy to use interface to the network protocol.

What I have so far:
I internally use the asyncio event loop and and the user can register 
event handler functions for specific events triggered by the network input.
Reduced to the essentials the architecture of my code looks like this:

class Client(asyncio.Protocol):

     def __init__(self, handler, server, port):
         self._handler = handler
         self._server = server
         self._port = port

     def run(self):
         loop = asyncio.get_event_loop()
         task = asyncio.Task(loop.create_connection(self, server, port))

     def data_received(self, data):
         # read data and call the appropriate handler methods on 

The user initializes a Client object, passing a handler to the 
constructor. The handler is an instance of a class that contains event 
handler methods implemented by the user. (The expected interface of a 
handler is defined in an abstract base class.)
Afterwards the user calls run() on the client to start processing.

So far this works, but only for applications that solely react to events 
from the network. Now I want to be able to use this library for network 
communication in interactive applications (command line or GUI), too. In 
this case it needs to be able to respond to user input, which must be 
somehow incorporated in the event loop. GUI libraries like PyQt even 
provide their own event loop.

So how do I integrate those aspects in my library?
Is asyncio the right choice?
Or does my whole approach goes in the wrong direction?

I would greatly appreciate any help and suggestions,


I posted this question to the tutor mailing list [2] but looks like 
python-list is a better place for it.

[1] The network protocol is IRC (Internet Relay Chat) but I think that 
does not really matter here.

More information about the Python-list mailing list