Skip to content

Commit

Permalink
feat: better runner support for asyncio
Browse files Browse the repository at this point in the history
  • Loading branch information
joamag committed Aug 23, 2021
1 parent 32a2898 commit 2bd79e3
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/netius/servers/echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@
__license__ = "Apache License, Version 2.0"
""" The license for the module """

import os

import netius

class EchoProtocol(netius.StreamProtocol):

def __init__(self, owner = None):
netius.StreamProtocol.__init__(self, owner=owner)
netius.StreamProtocol.__init__(self, owner = owner)

self.host = "0.0.0.0"
self.port = 90
Expand All @@ -52,9 +54,6 @@ def on_data(self, data):
netius.StreamProtocol.on_data(self, data)
self.send(data)

#@todo maybe move this to the upper layer
# as an utility, as this repeats itself many
# times
def serve(self, env = False, loop = None):
loop = netius.serve_stream(
lambda: self,
Expand All @@ -74,9 +73,28 @@ def serve_s(cls, env = False, loop = None):
protocol = cls.protocol()
return protocol.serve(env = env, loop = loop)

if __name__ == "__main__":
loop, protocol = EchoServer.serve_s()
async def main_asyncio():
# retrieves a reference to the event loop as we plan to use
# low-level APIs, this should return the default event loop
import asyncio
loop = asyncio.get_running_loop()
server = await loop.create_server(lambda: EchoProtocol(), "127.0.0.1", 8888)
async with server:
await server.serve_forever()

def run_native():
loop, _protocol = EchoServer.serve_s()
loop.run_forever()
loop.close()

def run_asyncio():
netius.run(main_asyncio())

if __name__ == "__main__":
if os.environ.get("ASYNCIO", "0") == "1" or\
os.environ.get("COMPAT", "0") == "1":
run_asyncio()
else:
run_native()
else:
__path__ = []

0 comments on commit 2bd79e3

Please sign in to comment.