简体   繁体   English

打印收到的服务器数据时出现问题

[英]Problems when print the server data received

I have the next problem: When i use this code for a EchoServer with the python asyncio library 我有下一个问题:当我将此代码用于带有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()

in this line 在这条线

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

when i use: end='' , the messages from the client without '\\n' don't log on the console and only show the messages received when client disconnected. 当我使用: end='' ,没有'\\n'来自客户端的消息不会登录控制台,仅显示客户端断开连接时收到的消息。 Like this: 像这样:

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

this message is show only when the client disconnect. 仅当客户端断开连接时才显示此消息。

but when i use '\\n' on the end of messages from the client the messages show on the console when the client send the messages. 但是,当我在来自客户端的消息末尾使用'\\n'时,客户端发送消息时,消息会显示在控制台上。 Like this: 像这样:

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

in this case in 3 diferents time and finally the client disconnect. 在这种情况下,需要3个不同的时间,最后客户端断开连接。 And when i use this line: 当我使用这一行:

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

without end='' ,works fine with the client messages without '\\n' in the end of messages. 没有end='' ,可以很好地处理消息末尾不带'\\n'的客户端消息。

I want to know why. 我想知道为什么。

The problem isnt with the console messages format, the problem is the time when the data received are show in the console. 问题与控制台消息格式无关,问题在于在控制台中显示接收到的数据的时间。

PS: sorry for my bad english. PS:对不起,我的英语不好。

You should manually flush stdout. 您应该手动刷新标准输出。

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

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

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