簡體   English   中英

打印收到的服務器數據時出現問題

[英]Problems when print the server data received

我有下一個問題:當我將此代碼用於帶有python asyncio庫的EchoServer時

import asyncio


class EchoServer(asyncio.Protocol):

    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        print('Message received: {}'.format(data.decode()), end='')
        self.transport.write(data + b'\n')

    def connection_lost(self, exc):
        print('Client disconnected...')


loop = asyncio.get_event_loop()
coro = loop.create_server(EchoServer, '127.0.0.1', 12345)
server = loop.run_until_complete(coro)
print('Listening on {}'.format(server.sockets[0].getsockname()))

try:
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    server.close()
    loop.close()

在這條線

print('Message received: {}'.format(data.decode()), end='')

當我使用: end='' ,沒有'\\n'來自客戶端的消息不會登錄控制台,僅顯示客戶端斷開連接時收到的消息。 像這樣:

Message received: testMessage received: testMessage received: testClient disconnected...

僅當客戶端斷開連接時才顯示此消息。

但是,當我在來自客戶端的消息末尾使用'\\n'時,客戶端發送消息時,消息會顯示在控制台上。 像這樣:

Message received: test
Message received: test
Message received: test
client disconnected...

在這種情況下,需要3個不同的時間,最后客戶端斷開連接。 當我使用這一行:

 print('Message received: {}'.format(data.decode()))

沒有end='' ,可以很好地處理消息末尾不帶'\\n'的客戶端消息。

我想知道為什么。

問題與控制台消息格式無關,問題在於在控制台中顯示接收到的數據的時間。

PS:對不起,我的英語不好。

您應該手動刷新標准輸出。

print('Message received: {}'.format(data.decode()), end='')
sys.stdout.flush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM