如何知道浏览器对等点何时在 aiortc 中断开连接?

How to know when a browser peer is disconnected in aiortc?

from aiortc import RTCPeerConnection

pc = RTCPeerConnection()
print(pc.connectionState)

错误:

C:\Users\Χρήστος\Desktop>python 123.py
Traceback (most recent call last):
  File "123.py", line 4, in <module>
    print(pc.connectionState)
AttributeError: 'RTCPeerConnection' object has no attribute 'connectionState'

这是 documentation of aiortc 中的第一个 属性,但我无法检索它。

注意:我也尝试过 connectionstatechange 事件,但两者都有效。

编辑: 这就是 pc 对象具有的方法:

['_RTCPeerConnection__assertNotClosed', '_RTCPeerConnection__assertTrackHasNoSender', '_RTCPeerConnection__connect', '_RTCPeerConnection__createDtlsTransport', '_RTCPeerConnection__createSctpTransport', '_RTCPeerConnection__createTransceiver', '_RTCPeerConnection__gather', '_RTCPeerConnection__getTransceiverByMLineIndex', '_RTCPeerConnection__getTransceiverByMid', '_RTCPeerConnection__localDescription', '_RTCPeerConnection__localRtp', '_RTCPeerConnection__remoteDescription', '_RTCPeerConnection__remoteRtp', '_RTCPeerConnection__setSignalingState', '_RTCPeerConnection__updateIceConnectionState', '_RTCPeerConnection__updateIceGatheringState', '_RTCPeerConnection__validate_description', '__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_add_event_handler', '_call_handlers', '_emit_handle_potential_error', '_emit_run', 'addIceCandidate', 'addTrack', 'addTransceiver', 'close', 'createAnswer', 'createDataChannel', 'createOffer', 'emit', 'getReceivers', 'getSenders', 'getStats', 'getTransceivers', 'listeners', 'on', 'once', 'remove_all_listeners', 'remove_listener', 'setLocalDescription', 'setRemoteDescription']

aiortc 使用 pyee 使 aiortc 事件驱动,正如您在官方 GitHub 示例 (webcam/webcam.py) 中看到的那样,您必须将事件侦听器放在名为 iceconnectionstatechange.

的事件上

检查下面的代码片段:

from aiortc import RTCPeerConnection


pc = RTCPeerConnection()


@pc.on("iceconnectionstatechange")
async def on_iceconnectionstatechange():
    print(f"ICE connection state is {pc.iceConnectionState}")

    if pc.iceConnectionState == "failed":
        # Do something

在你的问题中,你提到你已经尝试过 connectionstatechange 事件,但它实际上是 iceconnectionstatechange,这就是为什么第一次没有成功。