[英]Problems with Qt/C++ echo client + python echo server (no data received)
[英]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.