This commit is contained in:
yumoqing 2024-10-05 21:12:40 +08:00
parent e940467a2b
commit 5f0e01941c

102
rtcllm/wss.py Normal file
View File

@ -0,0 +1,102 @@
from websockets.client import connect
import websockets
from appPublic.background import Background
from appPublic.uniqueID import getID
from appPublic.dictObject import DictObject
class Wss:
"""
new session
session_type: p2p, aba, meeting
signaling data format
{
type:callRequest,
sessionid:kkkk,
sessiontype:...
from:
to:
}
"""
def __init__(self, app, wss_url, info=None, handler_name='sessionid'):
self.wss_url = wss_url
if info is None:
info = {
'id':getID()
}
self.ifno = info
self.ws = None
self.handler_name = handler_name
self.app = app
self.running = False
self.app.wss = self
self.handlers = {}
self.sessionhandlers = {}
self.peers = []
def add_handler(self, key, handler):
sef.handlers[key] = handler
def start(self):
loop = asyncio.get_running_loop()
f = asyncio.run_coroutine_threadsafe(self._start, loop)
return f.result()
def add_sessionhandler(self, sessiontype, handler):
self.sessionhandlers[sessiontype] = handler
async def _start(self):
self.ws = await connect(self.wss_url)
self.running = True
while self.running:
msg = await self.ws.recv()
data = DictObject(**json.loads(msg))
name = data.get(self.handler_name)
handler = self.handlers.get(name)
if handler is None:
handler = self.recvdata_handler
await handler(data)
async def recvdata_handler(self, data):
if data.type == 'info':
return
if data.type == 'session'
h = self.sessionhandlers.get(data.sessiontype)
i = h(data.from)
k = data.get(self.handler_name)
self.add_handler(k, i.recvdata_handler)
return
async def stop(self):
self.running = False
await self.ws.close()
async def restart(self):
try:
await self.stop()
except:
pass
await self.start()
async def send(self, dic):
dic['from'] = self.info
txt = json.dumps(dic)
try:
return await self.ws.send(txt)
except:
await self.restart()
return self.send(dic)
async def login(self):
d = DictObject()
d['from'] = self.info
d.type = 'login'
await self.send(d)
async def logout(self):
d = DictObject()
d['from'] = self.info
d.type = 'logout'
await self.send(d)