python asyncio流
客户端:
#! python3
import asyncio
import time
async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8885)
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()
await writer.wait_closed()
async def tcp_echo_client1(message):
try:
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8885)
async def read():
while True:
data = await reader.readline()
if not data:
break
# message = data.decode().strip()
print(f'Received: {data.decode()!r}')
async def write():
print(f'Send: {message!r}')
writer.write(message.encode())
await writer.drain()
async def ping():
await asyncio.sleep(5)
while True:
print("ping")
writer.write("ping\n".encode())
await writer.drain()
await asyncio.sleep(10)
await asyncio.gather(read(), write(), ping())
except ConnectionResetError as e:
print("断开连接")
print(e)
except Exception as e:
print("异常断开连接")
print(e)
# data = await reader.read(100)
# print(f'Received: {data.decode()!r}')
# print('Close the connection')
# writer.close()
# await writer.wait_closed()
if __name__ == '__main__':
asyncio.run(tcp_echo_client1("Hello World!\n"))
服务端:
#! python3
import asyncio
import time
async def handle_echo(reader, writer):
try:
addr = writer.get_extra_info('peername')
while True:
# 5秒接收不到数据就超时
data = await asyncio.wait_for(reader.readline(), timeout=30.0)
if not data:
print(f"断开连接")
break
message = data.decode()
print(f"Received {message!r} from {addr!r}")
# print(f"Send: {message!r}")
if message.strip() == "ping":
writer.write("pong\n".encode())
else:
fromServer = f"from server: {message.strip()}\n"
writer.write(fromServer.encode())
await writer.drain()
except TimeoutError:
print("超时断连")
writer.write("超时断开连接\n".encode())
await writer.drain()
finally:
print("Close the connection")
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(
handle_echo, '0.0.0.0', 8885)
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
print(f'Serving on {addrs}')
async with server:
await server.serve_forever()
if __name__ == '__main__':
asyncio.run(main())