Using asyncio in event-driven network library

T

Tobias M.

Hello,

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))
loop.run_until_complete(task)
loop.run_forever()

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

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.

Problem:
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.

Questions:
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,

Tobias

PS:
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.
[2] https://mail.python.org/pipermail/tutor/2013-December/099089.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top