当前位置:   article > 正文

python asyncio socket

python asyncio socket

python asyncio socket

asyncio对socket封装了一个高级api, 可以方便的启一个TCP server跟client

环境

  • python==3.8

文档

https://docs.python.org/3.8/library/asyncio-stream.html#asyncio.start_server

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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

Client

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))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/85291
推荐阅读
相关标签
  

闽ICP备14008679号