You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
94 lines
2.6 KiB
94 lines
2.6 KiB
import asyncio
|
|
|
|
class NGServer:
|
|
def __init__(self):
|
|
self.incoming_queue = asyncio.Queue()
|
|
self.outgoing_queue = asyncio.Queue()
|
|
self.client_reader = None
|
|
self.client_writer = None
|
|
|
|
async def handle_client(self, reader, writer):
|
|
self.client_reader = reader
|
|
self.client_writer = writer
|
|
while True:
|
|
data = await reader.read(1024)
|
|
if not data:
|
|
writer.close()
|
|
break
|
|
await self.incoming_queue.put(data)
|
|
|
|
async def handle_incoming(self, reader, writer):
|
|
while True:
|
|
data = await self.incoming_queue.get()
|
|
writer.write(data)
|
|
await writer.drain()
|
|
|
|
async def handle_outgoing(self, reader, writer):
|
|
while True:
|
|
data = await self.outgoing_queue.get()
|
|
writer.write(data)
|
|
await writer.drain()
|
|
|
|
async def read_from_server(self):
|
|
while True:
|
|
data = await self.client_reader.read(1024)
|
|
if not data:
|
|
self.client_writer.close()
|
|
break
|
|
await self.outgoing_queue.put(data)
|
|
|
|
async def start_server(self):
|
|
server = await asyncio.start_server(self.handle_client, host='localhost', port=8000)
|
|
async with server:
|
|
await server.serve_forever()
|
|
|
|
async def start_incoming_server(self):
|
|
server = await asyncio.start_server(self.handle_incoming, host='localhost', port=8001)
|
|
async with server:
|
|
await server.serve_forever()
|
|
|
|
async def start_outgoing_server(self):
|
|
server = await asyncio.start_server(self.handle_outgoing, host='localhost', port=8002)
|
|
async with server:
|
|
await server.serve_forever()
|
|
|
|
async def do_async_stuff(ng):
|
|
await asyncio.gather(ng.start_server(),ng.start_queue_server())
|
|
|
|
|
|
async def main():
|
|
"""
|
|
In this code, we're creating and running four separate coroutines:
|
|
|
|
1. start_server
|
|
2. start_incoming_server
|
|
3. start_outgoing_server
|
|
4. read_from_server.
|
|
|
|
We're also creating separate tasks for handling incoming and
|
|
outgoing data and adding them to the tasks list.
|
|
|
|
"""
|
|
ng = NGServer()
|
|
await asyncio.gather(
|
|
ng.start_server(),
|
|
ng.start_incoming_server(),
|
|
ng.start_outgoing_server(),
|
|
)
|
|
"""
|
|
tasks = [
|
|
ng.read_from_server(),
|
|
ng.handle_incoming(),
|
|
ng.handle_outgoing(),
|
|
]
|
|
await asyncio.gather(*tasks)
|
|
"""
|
|
|
|
def example():
|
|
"""
|
|
|
|
TODO: Implement some test cases so users understand
|
|
how to use it.
|
|
|
|
"""
|
|
# asyncio.run(main())
|