import time import asyncio from multiprocessing import Process from aiortc import RTCIceCandidate, RTCPeerConnection, RTCSessionDescription from openapi_client.rest import ApiException from pprint import pprint from aiortc import RTCPeerConnection, RTCSessionDescription from aiortc.sdp import candidate_from_sdp, candidate_to_sdp import uuid import openapi_client async def run(): # Defining the host is optional and defaults to http://127.0.0.1:8080 # See configuration.py for a list of all supported configuration parameters. configuration = openapi_client.Configuration( host = "http://127.0.0.1:8080" ) server_name="myserver" service_name="http1" # Enter a context with an instance of the API client with openapi_client.ApiClient(configuration) as api_client: # Create an instance of the API class peernet = openapi_client.PeerNetServiceApi(api_client) pc = RTCPeerConnection() channel = pc.createDataChannel("http1") # Define our handlers done = False session = "%s" % uuid.uuid4() @channel.on("open") def on_open(): print("Connection established!") @pc.on("datachannel") def on_datachannel(channel): @channel.on("message") def on_message(message): # Process the message, and send a response channel.send("Hello world") @pc.on("connectionstatechange") async def on_connectionstatechange(): if pc.connectionState == "failed": done = True await pc.close() @pc.on("icecandidate") async def on_icecandidate(candidate): peernet.peer_net_service_create_ice_candidatge(session=knock.offer.name, ice_candidate={ "candidate": candidate_to_sdp(obj), "sdpMid": obj.sdpMid, "sdpLineIndex": obj.sdpMLineIndex, }) offer = await pc.createOffer() await pc.setLocalDescription(offer) knock_name = "%s" % uuid.uuid4() peernet.peer_net_service_create_knock(server=server_name, service=service_name, knock={ "name": knock_name, "offer": { "name": session, "sdp": offer.sdp, }, }) # Poll the server waiting for answer answer = None while True: print("Checking for knocks") resp = peernet.peer_net_service_get_knock(server_name, service_name, knock_name) print("%s", resp) if resp.answer != None: answer = resp.answer break time.sleep(1) await pc.setRemoteDescription(RTCSessionDescription(sdp=answer.sdp, type="answer")) # Start connecting ice candidates! while not done: resp = peernet.peer_net_service_claim_ice_candidates(session) if resp.ice_candidates != None: time.sleep(1) continue for candidate in resp.ice_candidates: ice_candidate = candidate_from_sdp(candidate.candidate) ice_candidate.sdpMid = candidate.sdpMid ice_candidate.sdpMLineIndex = candidate.sdpLineIndex await pc.addIceCandidate(candidate) coro = run() # run event loop loop = asyncio.get_event_loop() try: loop.run_until_complete(coro) except KeyboardInterrupt: pass