gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:29:39 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com