Skip to content
Advertisement

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

from aiortc import RTCPeerConnection

pc = RTCPeerConnection()
print(pc.connectionState)

Error:

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'

It’s the first property in the documentation of aiortc but i cannot retrieved it.

Note: I also tried with connectionstatechange event but either that worked.

Edit: That’s the methods the pc object has:

['_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']

Advertisement

Answer

aiortc uses pyee for making aiortc event-driven and as you can see in the official GitHub example (webcam/webcam.py), you must put an event listener on an event named iceconnectionstatechange.

Checkout the code snippet below:

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

In your question you mentioned that you’ve tried connectionstatechange event but it’s actually iceconnectionstatechange and that’s why it didn’t work the first time.

Advertisement