• asyncio标准库5 TCP echo client and server


    server

    import asyncio
    
    async def handle_echo(reader, writer):
        data = await reader.read(100)
        message = data.decode()
        addr = writer.get_extra_info('peername')
        print("Received %r from %r" % (message, addr))
    
        print("Send: %r" % message)
        writer.write(data)
        await writer.drain()
    
        print("Close the client socket")
        writer.close()
    
    loop = asyncio.get_event_loop()
    coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
    server = loop.run_until_complete(coro)
    
    # Serve requests until Ctrl+C is pressed
    print('Serving on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    
    # Close the server
    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()
    

    client

    import asyncio
    
    async def tcp_echo_client(message, loop):
        reader, writer = await asyncio.open_connection('127.0.0.1', 8888, loop=loop)
    
        print('Send: %r' % message)
        writer.write(message.encode())
    
        data = await reader.read(100)
        print('Received: %r' % data.decode())
    
        print('Close the socket')
        writer.close()
    
    message = 'Hello World!'
    loop = asyncio.get_event_loop()
    loop.run_until_complete(tcp_echo_client(message, loop))
    loop.close()
    
    # server
    Serving on ('127.0.0.1', 8888)
    Received 'Hello World!' from ('127.0.0.1', 43000)
    Send: 'Hello World!'
    Close the client socket
    Received 'Hello World!' from ('127.0.0.1', 43006)
    Send: 'Hello World!'
    Close the client socket
    Received 'Hello World!' from ('127.0.0.1', 43008)
    Send: 'Hello World!'
    Close the client socket
    Received 'Hello World!' from ('127.0.0.1', 43010)
    Send: 'Hello World!'
    Close the client socket
    Received 'Hello World!' from ('127.0.0.1', 43012)
    Send: 'Hello World!'
    Close the client socket
    
    # client
    Send: 'Hello World!'
    Received: 'Hello World!'
    Close the socket
    
    Send: 'Hello World!'
    Received: 'Hello World!'
    Close the socket
    
    ....
    
  • 相关阅读:
    【CodeForces】[612C]Replace To Make Regular Bracket Sequence
    【POJ】[1363]Rails
    【POJ】[1363]Rails
    【杭电】[1022]Train Problem I
    【杭电】[1022]Train Problem I
    【杭电】[1873]看病要排队
    【杭电】[1873]看病要排队
    【HPU】[1714]感恩节KK专场——送给新生的礼物
    【HPU】[1714]感恩节KK专场——送给新生的礼物
    [leetcode]392. Is Subsequence 验证子序列
  • 原文地址:https://www.cnblogs.com/liujitao79/p/8601296.html
Copyright © 2020-2023  润新知