2

I work on WebRTC JS app and stcuk at a point where I need to crete a data channel. I have this part of code which actually works but openRTCDataChannel method is being executed twice:

        this.myRTCConnections[id][hash]=window.RTCPeerConnection?new RTCPeerConnection(this.RTCConfiguration,{optional:[]}):(window.mozRTCPeerConnection?new mozRTCPeerConnection(this.RTCConfiguration,{optional:[]}):new webkitRTCPeerConnection(this.RTCConfiguration,{optional:[]}));
        
        this.myRTCConnections[id][hash].ondatachannel=function(event){This.openRTCDataChannel(event,id,hash)}//first calling of openRTCDataChannel method
        this.openRTCDataChannel(false,id,hash)//second calling of openRTCDataChannel method
    
        this.openRTCDataChannel=function(event,id,hash,onOffer,initiator){
            var RTCDataChannelOptions={reliable:true},This=this
            if(!this.myRTCDataChannels[id])this.myRTCDataChannels[id]={}
            this.myRTCDataChannels[id][hash]=event&&event.channel?event.channel:this.myRTCConnections[id][hash].createDataChannel("myDataChannel",RTCDataChannelOptions)
            this.myRTCDataChannels[id][hash].onerror=function(error){log(error)}
            this.myRTCDataChannels[id][hash].onmessage=function(e){This.handleIncomingRTCMessage(e.data,id,hash)}
            this.myRTCDataChannels[id][hash].onclose=function(e){This.onSignalingServerLeave(false,id,hash)}
            this.myRTCDataChannels[id][hash].onopen=function(e){This.onRTCDataChannelOpen(id,hash,onOffer,initiator)}
        }

If I comment first or second calling if openRTCDataChannel method some of my peers can exchange data between themselves and some can not.

So the problem is that if I want my code to work I need to execute openRTCDataChannel method twice in two different ways. What am I doing wrong and what is the best way to start data channel which would work in all browsers?

Any help appreciated!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SuperYegorius
  • 754
  • 6
  • 24
  • may this answer helps https://stackoverflow.com/questions/43788872/how-are-data-channels-negotiated-between-two-peers-with-webrtc/43788873#43788873 – Erlang Parasu May 06 '22 at 08:26

1 Answers1

0

Ok. SO it seems I have found out what is wrong here.

Peer that initiates the connection and sending an offer should create data channel this way:

this.openRTCDataChannel(false,id,hash)

And another peer which accepts the offer and sending an answer should use this:

this.myRTCConnections[id][hash].ondatachannel=function(event){This.openRTCDataChannel(event,id,hash)}

I checked this in Mozilla and Chrome and it worked for me. Correct me if I am wrong.

SuperYegorius
  • 754
  • 6
  • 24