How to run a coroutine and wait for its result from a sync func

240 views Asked by At

I am trying to run a python socketIO client along side a server. Basically when the server gets a viewer event, the client fires another connection to an upstream server. It then tries to establish a WebRTC connection based on aiortc.


# sio client 
sioClient = socketio.Client()

# sio server 
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
sioServer = SocketIO(app, async_mode=async_mode)


@app.route("/")
def index():
    print("Get request '/'")
    return render_template('index.html')

@sioClient.on('connect')
def sio_connect():
    sioClient.emit('viewer', {'foo': 'bar'})
    print('proxy is connected to server, SID = ', sioClient.sid)


@sioClient.on('offer')
def sio_offer(broadcasterId,broadcasterDescription): 
    print("offer event")
    peerConnection = RTCPeerConnection()
    peerConnection.setRemoteDescription(broadcasterDescription)

    print("remoteDescription is ", peerConnection.remoteDescription)

@sioServer.on('viewer')
def handle_viewer_event(arg1):
    print('received args: ' + arg1["data"])
    sioClient.connect('http://localhost:4000')
    print('proxy sid is', sioClient.sid)


if __name__ == '__main__':
    sioServer.run(app)

Currently the @sioClient.on('connect') works fine and successfully emits another 'viewer' event to the upstream server. However when an 'offer' event comes back, I get the below error:

RuntimeWarning: coroutine 'RTCPeerConnection.setRemoteDescription' was never awaited
  peerConnection.setRemoteDescription(broadcasterDescription)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
remoteDescription is  None

I sort of understand this is because 'RTCPeerConnection.setRemoteDescription' is an asynchronous coroutine, but I don't know how to wait for it synchronously.

I have tried to make sio_offer an asynchronous func like below:

@sioClient.on('offer')
async def sio_offer(broadcasterId,broadcasterDescription): 
    print("offer event")
    peerConnection = RTCPeerConnection()
    await peerConnection.setRemoteDescription(broadcasterDescription)

    print("remoteDescription is ", peerConnection.remoteDescription)

But the whole block doesn't execute anymore upon an 'offer' event. I've seen a few suggestions around asyncio eventloop. But I am a python beginner and got very confused...

It will be appreciated if anyone can shed a bit light! Thanks in advance!

0

There are 0 answers