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个循环运行 我的代码有什么问题?
答案 0 :(得分:5)
这可能是不可能的。 Guido van Rossum stated before that he didn't want recursive event loops 而且您似乎正在创建嵌套的事件循环
答案 1 :(得分:2)
在您的代码之前,只需编写这些行
!pip install nest_asyncio
import nest_asyncio
nest_asyncio.apply()