WebRTC onicecandidate event

2019-02-25 04:27发布

问题:

I have the following callback for the onicecandidate event of RTCPeerConnection:

function iceCallback(event) {
    if (event.candidate) {
        var candidate = event.candidate;
        socSend("candidate", candidate. event.target.id);
    }
}

I am able to read the candidate from the event.candidate. But when I try to read the event.target.id, I get an exception, cannot read property target of undefined.

"id" is a property I previously created for the RTCPeerConnection. This is for a multiuser video chat.

I am trying to figure out which RTCPeerConnection fired the onicecandidate event so I know to which client I need to send the icecandidate. I am using the adapter.js library.

回答1:

I assumed that some part of your code would be like below, I have just added a simple modification:

peerConnections ={};

function createNewConncection(id){
    var pc = new RTCPeerConnection();
    pc.onaddstream = ...
    ...

    //pc.onicecandidate = iceCallback;  // OLD CODE
    pc.onicecandidate = iceCallback.bind({pc:pc, id:id});  // NEW CODE
    peerConnections[id] = pc;
}

function iceCallback(event) {
    if (event.candidate) {
        var candidate = event.candidate;
        //socSend("candidate", candidate. event.target.id);     // OLD CODE
        socSend("candidate", this.id);          // NEW CODE
    }
}