While looking over the new features in Python 3.x, I was intrigued by the asyncio library being added. After looking at the reference documentation, I decided to play around with it a little bit.
This worked well until I tried to make it work for multiple clients, and keep a list of all active/connected clients. This introduced a cyclic dependency between the server class and the session class.
Now, I've tried a few different ways to resolve this; however, there doesn't appear to be any way for me to get at this data directly from the server class through any method/functional call.
While I have been able to workaround this by using a "lazy" import, it seems like this my be indicative of either a poor design, a lack of understanding of the library itself, or a combination of both.
Code wise, I have a small sample put together. Am I missing an obvious solution here, or does my organization need to change to better support the functionality provided by the asyncio library?
__main__.py:
from network.server import Server
def main(args=None):
s = Server()
try:
s.run()
except KeyboardInterrupt:
pass
s.close()
if __name__ == "__main__":
main()
server.py:
import asyncio
from network.session import Session
class Server:
sessionList = []
def __init__(self):
self.handler = None
self.loop = asyncio.get_event_loop()
self.coro = self.loop.create_server(Session, 'localhost', 1234)
def run(self):
self.handler = self.loop.run_until_complete(self.coro)
print('Server Running On: {}'.format(self.handler.sockets[0].getsockname()))
self.loop.run_forever()
def close(self):
self.handler.close()
self.loop.run_until_complete(self.handler.wait_closed())
self.loop.close()
@staticmethod
def add_session(session):
Server.sessionList.append(session)
@staticmethod
def del_session(session):
Server.sessionList.remove(session)
session.py:
import asyncio
class Session(asyncio.Protocol):
def __init__(self):
from network.server import Server
self._transport = None
Server.add_session(self)
def connection_made(self, transport):
self._transport = transport
self._transport.write('Echo Server Example\r\n\r\n'.encode())
def data_received(self, data):
self._transport.write(data)
def eof_received(self):
self._transport.close()
def connection_lost(self, exc):
from network.server import Server
Server.del_session(self)
if exc is not None:
self._transport.close()