【问题标题】:Facing issue coroutine 'AsyncSocketClient.connect' was never awaited Tornado ( Socket )面对问题协程'AsyncSocketClient.connect'从未等待龙卷风(套接字)
【发布时间】:2023-03-15 00:31:01
【问题描述】:

我正在建立一个套接字连接(Tornado Web 框架。)

我的代码:

main.py

def main():
    io_loop = tornado.ioloop.IOLoop.instance()
    decoder = AsyncSocketClient(host = "localhost", port = 8080, try_reconnect=True , io_loop= io_loop)
    decoder.connect()
    io_loop.start()

if __name__ == '__main__':
    main()

AsyncSocketClient.py

class AsyncSocketClient():
    def __init__(self, host,io_loop , port, try_reconnect=False):
        self.ws_host = host
        self.ws_port = port
        self.io_loop = io_loop

    async def connect(self):
        class AsyncSocket(socket.socket):
            def write_message(self, message):
                message = message.encode()
                self.send(message)
        try:
            self._ws_connection = AsyncSocket(socket.AF_INET, socket.SOCK_STREAM, 0)
            self._ws_connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            await self._ws_connection.connect((self.ws_host, self.ws_port))
            self._ws_connection.setblocking(0)
            self.add_to_ioloop(self.io_loop)
            self._on_connection_success()
        except Exception as e:
            time.sleep(1)
            self.close()

    def add_to_ioloop(self, io_loop):
        io_loop.add_handler(self._ws_connection.fileno(), self._handle_events, io_loop.ERROR)
        io_loop.update_handler(self._ws_connection.fileno(), io_loop.READ)

    async def close(self):
        if not self._ws_connection:
            raise RuntimeError('Web socket connection is already closed.')

        await self._ws_connection.close()
        self._ws_connection = None
        self._on_connection_close()

    async def _on_connection_close(self):
        print("Connection Closed from " + self.ws_host + ":" + str(self.ws_port))
        if self.try_reconnect:
            print("Retrying to connect " + self.ws_host + ":" + str(self.ws_port))
            self.connect()

    def _on_connection_success(self):
        print("Connected to " + self.ws_host + ":" + str(self.ws_port))

当我运行 main.py 时,我收到以下错误:

main.py: RuntimeWarning: coroutine 'AsyncSocketClient.connect' was never awaited
  decoder.connect()

我尝试过使用 run_sync() 方法但我无法达到结果。我已经在run_sync() 中传递了 lambda 并且我能够连接但是在执行此行之后什么都没有:

await self._ws_connection.connect((self.ws_host, self.ws_port))

【问题讨论】:

    标签: python sockets asynchronous async-await tornado


    【解决方案1】:

    由于connect是协程,你需要await它。为此,您还必须将 main 函数转换为协程。

    但这似乎是多余的,因为您可以使用 run_sync 实现类似的效果:

    if __name__ == '__main__':
        decoder = AsyncSocketClient(...)
        io_loop = tornado.ioloop.IOLoop.current()
        io_loop.run_sync(decoder.connect)
    

    顺便说一句,如果您尝试实现 websocket 客户端,请知道tornado already comes with one

    【讨论】:

    • 我尝试了 io_loop.run_sync(decoder.connect) 但我收到错误:object NoneType can't be used in 'await' expression 此错误发生在这一行:await self._ws_connection。连接((self.ws_host,self.ws_port))
    • @SharvinShah 那是因为socket.connect 方法不是协程。因此,您不能await 它。对于异步套接字,请使用tornado's tcpclientasyncio Streams
    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多