Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用asyncio.Protocol子类定期发送数据_Python 3.x_Python Asyncio - Fatal编程技术网

Python 3.x 如何使用asyncio.Protocol子类定期发送数据

Python 3.x 如何使用asyncio.Protocol子类定期发送数据,python-3.x,python-asyncio,Python 3.x,Python Asyncio,我有asyncio.Protocol子类 class MyProtocol(Protocol): def __init__(self, exit_future): self.exit_future = exit_future def connection_made(self, transport): self.transport = transport def data_received(self, data): pas

我有asyncio.Protocol子类

class MyProtocol(Protocol):
    def __init__(self, exit_future):
        self.exit_future = exit_future

    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        pass

    def eof_received(self):
        self.exit_future.set_result(True)

    def connection_lost(self, exc):
        self.exit_future.set_result(True)
和使用创建的网络连接

while True:
    try:
        exit_future = Future(loop=loop)
        transport, protocol = await loop.create_connection(lambda: MyProtocol(exit_future), host, port)

        await exit_future
        transport.close()
    except:
        pass
现在的问题是:如何发送一些外部事件发生时的数据?例如,当asyncio.Queue不为空时(Queue.get不会阻塞),填充该队列的内容与asyncio无关?什么是调用transport.write的最正确方法

我如何发送一些外部事件发生时的数据

最简单的方法是在
connection\u made
中生成协同程序,并让它在“后台”处理事件:

请注意,从长远来看,将
create_connection
替换为并从头开始使用streams API可能是值得的。这样,您就可以一直使用协同路由,而不用担心回调/协同路由阻抗不匹配

在一个不相关的注释中,<代码>尝试后面跟着<代码>,除了:PASS是一个-考虑捕获一个特定的异常,或者至少记录异常。< /P>

def connection_made(self, transport):
    self.transport = transport
    loop = asyncio.get_event_loop()
    self._interesting_events = asyncio.Queue()
    self.monitor = loop.create_task(self._monitor_impl())

def connection_lost(self, exc):
    self.exit_future.set_result(True)
    self.monitor.cancel()

async def _monitor_impl(self):
    while True:
        # this can also await asyncio.sleep() or whatever is needed
        event = await self._interesting_events.get()
        self.transport.write(...)