美文网首页
Master asyncio TCP connection in

Master asyncio TCP connection in

作者: yingshaoxo | 来源:发表于2017-08-07 20:37 被阅读415次

    Copy from: https://docs.python.org/3/library/asyncio.html

    Today I'm gonna talk about how to programming with asyncio TCP connection. For general, you won't have much problems with server end. So I'm gonna talk about client.

    import asyncio
    
    class EchoClientProtocol(asyncio.Protocol):
        def __init__(self, message, loop):
            self.message = message
            self.loop = loop
    
        def connection_made(self, transport):
            transport.write(self.message.encode())
            print('Data sent: {!r}'.format(self.message))
    
        def data_received(self, data):
            print('Data received: {!r}'.format(data.decode()))
    
        def connection_lost(self, exc):
            print('The server closed the connection')
            print('Stop the event loop')
            self.loop.stop()
    
    loop = asyncio.get_event_loop()
    message = 'Hello World!'
    coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
                                  '127.0.0.1', 8888)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
    

    If we just look at this example, you'll find a lot of interesting things that asyncio already did for us.


    Before we get started, I'd like to tell you some fundamental data types that you should know first: protocol and transport.

    https://docs.python.org/3/library/asyncio-protocol.html#protocols
    https://docs.python.org/3/library/asyncio-protocol.html#basetransport

    protocol, as we can see, just a class definition that defines what we should do when we connected to a server.
    transport is a higher abstraction and encapsulation of socket, which allows us forget how socket do data exchanging. So we can use it sending data directly.


    Firstly, we got connection_made callback function. This function allows us do something when connection has been created.

    From this function, we'll get a transport instance class, that allows us sending message to server in later. So normally we wanna keep it as a global variable.

    Then we got data_received callback function, which get data from server when message comes.

    So if everything just OK, I'd rather make a reply client in this way:

    import asyncio
    
    class EchoClientProtocol(asyncio.Protocol):
        def __init__(self, message, loop):
            self.message = message
            self.loop = loop
    
        def connection_made(self, transport):
            transport.write(self.message.encode())
            print('Data sent: {!r}'.format(self.message))
    
            self.transport = transport
    
        def data_received(self, data):
            print('Data received: {!r}'.format(data.decode()))
            
            self.transport.write(data)
    
        def connection_lost(self, exc):
            print('The server closed the connection')
            print('Stop the event loop')
            self.loop.stop()
    
    loop = asyncio.get_event_loop()
    message = 'Hello World!'
    coro = loop.create_connection(lambda: EchoClientProtocol(message, loop),
                                  '127.0.0.1', 8888)
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
    

    相关文章

      网友评论

          本文标题:Master asyncio TCP connection in

          本文链接:https://www.haomeiwen.com/subject/matucxtx.html