我正在尝试使用aiortc
python 包实现 p2p 聊天。我在客户端和服务器中有以下代码。
async def run_server(sname, oname):
signalling = HTTPLongPollSignalling(sname, oname)
pc = RTCPeerConnection()
chat = pc.createDataChannel("chat")
print("Creating channel", chat.label, "id:", chat.id)
pch = pc.createDataChannel("ping")
print("Creating channel", pch.label, "id:", pch.id)
print("Waiting for client")
async def send_pings():
while True:
channel_send(pch, "ping %d" % current_stamp())
await asyncio.sleep(20)
@pch.on("open")
def on_open():
print("channel ping opened")
asyncio.ensure_future(send_pings()) #Comment this
@pch.on("message")
def on_message(message):
print(pch.label, "(ping) <", message)
if isinstance(message, str) and message.startswith("pong"):
elapsed_ms = (current_stamp() - int(message[5:])) / 1000
print(" RTT %.2f ms" % elapsed_ms)
@chat.on("open")
def on_chat_connect():
# Set channel.send as sendCb in UI
ui.setSendCb(lambda msg: (
print("calling send on ch", chat.label, "id:", chat.id, "with", repr(msg)),
chat.send(msg)))
ui.postJob('append_msg', ("system", "Channel established: Chat"))
chat.send("Channel established: Chat")
@chat.on("message")
def on_chat_msg(msg):
print(chat.label, chat.id, ">", msg)
ui.postJob('append_msg', (oname, msg))
print(chat.label, "msg added")
await pc.setLocalDescription(await pc.createOffer())
# Share offer to other end
# recv answer from other end
await pc.setRemoteDescription(answer)
while True:
await asyncio.sleep(1)
async def run_client(sname, oname):
signalling = HTTPLongPollSignalling(sname, oname)
pc = RTCPeerConnection()
@pc.on("datachannel")
def on_datachannel(channel):
print(channel.label, "with id", channel.id, "-", "created by remote party")
if channel.label == 'ping':
@channel.on("message")
def on_message(message):
print(channel.label, "<", message)
if isinstance(message, str) and message.startswith("ping"):
# reply
channel_send(channel, "pong" + message[4:])
elif channel.label == 'chat':
print ("Setting cb on channel chat")
ui.setSendCb(lambda msg:(
print("calling send on ch", chat.label, "id:", chat.id, "with", repr(msg)),
chat.send(msg)))
@channel.on('message')
def on_chat_msg(msg):
print(channel.label, ">", msg)
ui.postJob("append_msg", (oname, msg))
print("Setting cb on channel chat DONE")
# Get offer from serve
await pc.setRemoteDescription(offer)
await pc.setLocalDescription(await pc.createAnswer())
# share answer with serve
while True:
await asyncio.sleep(1)
在此代码中,频道 ping 正在通过频道聊天接收数据。也就是说,如果我们不在 ping 通道上发送任何内容,那么聊天通道也不会收到任何数据。例如,如果我们asyncio.ensure_future(send_pings())
在打开的 ping 频道中发表评论,则永远不会调用聊天频道接收。
我是异步编程的新手,所以请从异步的角度提出任何不正确的建议。