【问题标题】:'Cannot run the event loop while another loop is running') RuntimeError websockets?'在另一个循环运行时无法运行事件循环')RuntimeError websockets?
【发布时间】:2018-03-07 14:18:48
【问题描述】:
import asyncio
    import json
    import websockets
    from mongodb import *


    class WebSocketRequest:
        def __init__(self, websocket):
            self.websocket = websocket

        async def login(self):
            data = await self.websocket.recv()
            j = json.loads(data)
            for i in j:
                if i == 'email':
                    email = j[i]
                if i == "pass":
                    password = j[i]
            user = users.find_one({"email":email})
            if user == None:
                msg = 400
            else:
                msg = 200
            await websocket.send(str(msg))

        async def register(self):
            data = await self.websocket.recv()
            j = json.loads(data)
            print(j)

        async def run(self):

            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            asyncio.ensure_future(self.login())
            asyncio.ensure_future(self.register())
            loop.run_forever()

    class WebsocketServer:
        def __init__(self, localhost,port):
            self.localhost = localhost
            self.port = port


        async def hello(self, websocket, path):
            req = WebSocketRequest(websocket)
            await req.run()

        def run(self):
            print("opening")
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)

            start_server = websockets.serve(self.hello, self.localhost, self.port)

            asyncio.get_event_loop().run_until_complete(start_server)
            asyncio.get_event_loop().run_forever()
    if __name__=='__main__':
        localhost, port = '127.0.0.1', 5678
        web = WebsocketServer(localhost, port)
        web.run()

我正在尝试使用 WebSockets 构建聊天应用服务器。我有3种方法- 登录、注册和聊天。我检查用户是否登录并将他重定向到前端注册。我正在尝试使用类在一个脚本中运行 3 种方法。 我收到一条错误消息,因为运行了 2 个循环。
我的代码有什么问题?

【问题讨论】:

    标签: python python-3.x websocket


    【解决方案1】:

    这可能是不可能的。 Guido van Rossum stated before that he didn't want recursive event loops 看起来你正在创建一个嵌套的事件循环

    【讨论】:

      【解决方案2】:

      在你的代码之前只写那些行

      !pip install nest_asyncio
      import nest_asyncio
      nest_asyncio.apply()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多