'在另一个循环正在运行时无法运行事件循环') RuntimeError websockets? [英] 'Cannot run the event loop while another loop is running') RuntimeError websockets?

查看:26
本文介绍了'在另一个循环正在运行时无法运行事件循环') RuntimeError websockets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a chat-app server using WebSockets. I have 3 methods - login, register and chat. I check if a user login or not and redirect him to register in a front end. I am trying to run 3 methods in one script using classes. I got an error message because there 2 loops run.
What is the problem in my code?

推荐答案

这可能是不可能的.Guido van Rossum 之前表示他不想要递归事件循环看起来你正在创建一个嵌套的事件循环

It might not be possible. Guido van Rossum stated before that he didn't want recursive event loops And it seems like you're creating a nested event loops

这篇关于'在另一个循环正在运行时无法运行事件循环') RuntimeError websockets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆