簡體   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