如何使用AsyncI实现UDP和TCP套接字

2024-04-26 06:23:52 发布

您现在位置:Python中文网/ 问答频道 /正文

所以技术上我已经创建了一个TCP监听套接字,一切正常。你知道吗

它只需获取tcp json消息并将其吐出即可。你知道吗

class TCPListener(Base):
    def __init__(self,
                 address,
                 port,
                 buffer,
                 backlog,
                 **kwargs):
        self.tcp_address = address
        self.tcp_port = port
        self.tcp_buffer = buffer
        self.tcp_asyncio_backlog = backlog
        self.queue = queue.Queue()

    def __await__(self):
        self._server = yield from asyncio.start_server(
            self.__on_message,
            host=self.tcp_address,
            port=self.tcp_port,
            backlog=self.tcp_asyncio_backlog
        )
        return self

    async def __on_message(self, reader, writer):
        message = await reader.read(self.tcp_buffer)
        try:
            json_encoded = json.loads(message.decode('UTF-8').strip())
            self.queue.put(json_encoded)
        writer.close()

    def start(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        asyncio.ensure_future(self, loop=loop)


    def receive(self):
        while self.queue.empty():
            sleep_random = random.randint(0, 1000)
            time.sleep(sleep_random / 1000.0)

        if not self.queue.empty():
            return self.queue.get(block=False)
        return '', ''

现在我正在尝试使这段代码同时适用于TCP和UDP侦听器。我想知道我能保留什么功能,以及如何在两个听者之间共享它们,对于如何实现这一点我有点不知所措!如果我没有弄错的话,我应该使用“create\u datagram\u endpoint”,但是仍然不知道如何将它与这个类和函数粘合在一起。你知道吗


Tags: selfloopasynciojsonmessagereturnqueueport