python - '无法在另一个循环运行时运行事件循环')RuntimeError websockets?

标签 python python-3.x websocket

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 个循环在运行。
我的代码有什么问题?

最佳答案

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

关于python - '无法在另一个循环运行时运行事件循环')RuntimeError websockets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49154106/

相关文章:

python - 有没有办法在不实例化对象的情况下列出类的属性?

javascript - 向其他人显示屏幕上的光标而不过多影响资源的最佳方式

python - 与标准网络服务器一起扩展解耦的实时服务器

python - 使用比较函数的排序函数

python-3.x - 来自 sklearn 的机器学习

python-3.x - 如何识别质心点是否接触到一条线?

html - websocket客户端能否从80/443以外的不同端口连接到websocket服务器

python - 在 Python 中创建拉丁方程序

python - 如何在Python中使用Excel公式(宏)处理Excel文件(xlsx,xls)

Python:计算字符串中相互跟随的字符