繁体   English   中英

Python asyncio 套接字服务器吃错误(不显示任何错误)

[英]Python asyncio socket server eating errors (not displaying any errors)

编辑我的问题以提供更多信息和可重现的示例。

我不确定是否有人可以在这里帮助我。 但是我的 asyncio 套接字服务器有一些问题。

可以看到,在server.py的第18行,有一行会导致值错误,不能把""改成int。 这是故意的,因为出于某种原因,此行上的错误永远不会输出到控制台。

当客户端连接到服务器时, print("here1")行运行,但由于第 18 行的错误,之后的行不会运行。我需要将此错误输出到控制台,但它无处出现。 我很困惑,在网上找不到任何关于为什么 asyncio 可以吃掉错误而不显示错误的信息。

我试图通过使用日志记录模块来查看任何错误,但即使这样也没有显示任何错误..

import logging
logging.basicConfig(level=logging.ERROR)

导致错误的行肯定正在运行。

我已将所有代码提取到下面一组较小的可重现文件中。

服务器.py

import asyncio


class Server:
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port

    async def start_server(self):
        print("Server online")
        server = await asyncio.start_server(self.handle_events, self.host, self.port)
        async with server:
            await server.serve_forever()

    async def handle_events(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
        while True:
            print("here1")
            int("")
            print("here2")
            data = await reader.read(1024)
            if not data:
                continue
            print(f"received: {data}")


async def start():
    host = "127.0.0.1"
    port = 55551
    server = Server(host=host, port=port)
    server_task = asyncio.create_task(server.start_server())
    await asyncio.gather(server_task)

if __name__ == "__main__":
    asyncio.run(start())

客户端.py

import asyncio


class Client:
    def __init__(self, host: str, port: int):
        super().__init__()
        self.host = host
        self.port = port
        self.writer = None
        self.reader = None

    async def start_connection(self):
        self.reader, self.writer = await asyncio.open_connection(host=self.host, port=self.port)
        await self.message_handler()

    async def message_handler(self):
        while True:
            await asyncio.sleep(0)
            data = await self.reader.read(1024)
            if not data:
                continue

            await self.writer.drain()


async def start():
    host = "127.0.0.1"
    port = 55551
    server = Client(host=host, port=port)
    server_task = asyncio.create_task(server.start_connection())
    await asyncio.gather(server_task)

if __name__ == "__main__":
    asyncio.run(start())

因为它甚至没有调用handle_events函数。

import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 55555)

    print(f'Send: {message!r}')
    writer.write(message.encode())
    await writer.drain()

    data = await reader.read(100)
    print(f'Received: {data.decode()!r}')

    print('Close the connection')
    writer.close()

asyncio.run(tcp_echo_client('Hello World!'))

我只是从文档中复制了这个,所以我可以测试它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM