赞
踩
asyncio对socket封装了一个高级api, 可以方便的启一个TCP server跟client
https://docs.python.org/3.8/library/asyncio-stream.html#asyncio.start_server
import asyncio from asyncio import StreamReader, StreamWriter async def echo(reader: StreamReader, writer: StreamWriter): data = await reader.read(10) message = data.decode() addr = writer.get_extra_info('peername') print(f"Received {message!r} from {addr!r}") print(f"Send: {message!r}") writer.write(data) await writer.drain() writer.close() async def main(host, port): server = await asyncio.start_server(echo, host, port) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever() asyncio.run(main("127.0.0.1", 8888))
import asyncio async def tcp_echo_client(message): reader, writer = await asyncio.open_connection('127.0.0.1', 8888) print(f'Send to server: {message!r}') writer.write(message.encode()) await writer.drain() data = await reader.read(100) print(f'Received from server: {data.decode()!r}') writer.close() await writer.wait_closed() if __name__ == '__main__': while True: send_msg = input("send: ") asyncio.run(tcp_echo_client(send_msg))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。