我用 asyncio 创建了一个套接字服务器。从套接字读取是立即完成的,但写入套接字必须根据条件从另一个类调用。我的实现不起作用。请帮忙
class MyAsyncioHandler:
def __init__(self, reader, writer):
self.reader = reader
self.writer = writer
self._serverThread = _Thread(self)
self._serverThread.start()
async def handle_read(self):
buf = await self.reader.read(8192)
print(buf)
async def handle_write(self, data):
self.writer.write(data)
await self.writer.drain()
self.writer.close()
class NewServer:
def __init__(self, host, port):
self.host = host
self.port = port
async def handle_client(self, reader, writer):
handler = MyAsyncioHandler(reader, writer)
await handler.handle_read()
async def _run(self):
server = await asyncio.start_server(
self.handle_client, self.host, self.port
)
addr = server.sockets[0].getsockname()
log(f"Server: Listen {addr}", INFO)
async with server:
await server.serve_forever()
def serve(self):
asyncio.run(self._run())
class _Thread(Thread):
def __init__(self, handler):
Thread.__init__(self)
self._handler = handler
def run(self):
if data:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(self._handler.handle_write(data))
server = NewServer('localhost', 5000)
server.serve()
你可以尝试:
import asyncio
class MyAsyncioHandler:
def __call__(self, reader, writer):
async def _inner():
await self.handle_read(reader)
data_to_send = b"Response data"
await self.handle_write(writer, data_to_send)
return _inner()
async def handle_read(self, reader):
data = await reader.read(8192)
if data:
print(f"Received data: {data.decode()}")
async def handle_write(self, writer, data):
print("Write", data)
writer.write(data)
await writer.drain()
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(MyAsyncioHandler(), "127.0.0.1", 5000)
addr = server.sockets[0].getsockname()
print(f"Serving on {addr}")
async with server:
await server.serve_forever()
if __name__ == "__main__":
asyncio.run(main())
运行此脚本将在
127.0.0.1:5000
上启动服务器。
在其他终端上,您可以使用以下命令将数据发送到服务器:
$ echo "Hello World" | curl telnet://127.0.0.1:5000