Что я пытаюсь сделать:
Как бы я обработал пользователя, отключающегося от приложения с помощью веб-сокетов, но все же позволяющего другим пользователям, подключенным к серверу, продолжать?Если я запускаю это, все мои пользователи могут подключиться, но когда один пользователь отключается, сервер выдает исключение:
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1001 (going away), no reason
Вот мой код:
#!/usr/bin/env python
import asyncio
import websockets
import json
import ssl
import pathlib
users = {}
connected = set()
async def sendTo(websocket, message):
await websocket.send(json.dumps(message))
async def signaling(websocket, path):
while(True):
#get message from client
message = await websocket.recv()
#decode message
try:
data = json.loads(message)
except:
print("Not valid json")
print(message)
if data['type'] == "login":
if data['name'] in users:
await sendTo(websocket,{"type": "login",
"Success":False})
print("sentTo Failed, username already taken")
else:
users[data['name']] = {"websocket": websocket}
await sendTo(websocket, {"type": "login",
"Success":True})
#send all of the users a list of names that they can connect to
for key, val in users.items():
await sendTo(val['websocket'], {"type":"userLoggedIn",
"names":list(users.keys())})
elif data['type'] == "offer":
print("Sending offer to: {}".format(data['sentTo']))
#if UserB exists then send him offer details
conn = users[data['sentTo']]['websocket']
users[data['name']]['sentTo'] = data['sentTo']
if conn is not None:
#setting that UserA connected with UserB
#websocket['otherName'] = data['name']
#send to connection B
await sendTo(conn, {"type": "offer",
"offer":data['offer'],
"name":data['name']})#send the current connections name
#add other user to my list for retreaval later
print("offerFrom: {}, offerTo: {}".format(data['name'], data['sentTo']))
elif data['type'] == "answer":
print("Sending answer to: {}".format(data['sentTo']))
conn = users[data['sentTo']]['websocket']
users[data['name']]['sentTo'] = data['sentTo']
if conn is not None:
#setting that UserA connected with UserB
await sendTo(conn, {"type": "answer",
"answer":data['answer']})
#add other user to my list for retreaval later
print("answerFrom: {}, answerTo: {}".format(data['name'], data['sentTo']))
elif data['type'] == "candidate":
print("Sending candidate ice to: {}".format(users[data['name']]['sentTo']))
sendingTo = users[data['name']]['sentTo']#Who am I sending data to
conn = users[sendingTo]['websocket']
if conn is not None:
#setting that UserA connected with UserB
await sendTo(conn, {"type": "candidate",
"candidate":data['candidate']})
print("candidate ice From: {}, candidate ice To: {}".format(data['name'], users[data['name']]['sentTo']))
elif data['type'] == "candidate":
print("Disconnecting: {}".format(users[data['name']]['sentTo']))
sendingTo = users[data['name']]['sentTo']#Who am I sending data to
conn = users[sendingTo]['websocket']
if conn is not None:
#setting that UserA connected with UserB
await sendTo(conn, {"type": "leave"})
else:
print("Got another Message: {}".format(data))
#closing the socket is handled?
#await websocket.send(json.dumps({"msg": "Hello_World!!!!"}))
if __name__ == "__main__":
print("Starting Server")
#path.abspath("/opt/cert")
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(
pathlib.Path("/opt/cert/nginx-selfsigned.crt").with_name('nginx-selfsigned.crt'), pathlib.Path("/opt/cert/nginx-selfsigned.key").with_name('nginx-selfsigned.key'))
asyncio.get_event_loop().run_until_complete(
websockets.serve(signaling, '192.168.11.138', 8765, ssl=ssl_context))
asyncio.get_event_loop().run_forever()
print('ended')
users = {}
Что япробовал
Я пытался добавить исключение, когда мы ожидаем сообщения и вырываемся из цикла, но оно не позволяет другим пользователям продолжать использовать приложение.