Master asyncio TCP connection in Python3 (1

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()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容