DataChannel Webrtc Swift

时间:2017-03-14 13:58:59

标签: swift webrtc rtcdatachannel

我想创建一个数据通道。但是我在实施这个方面遇到了一些困难。我添加了在“来电方”上运行的代码:

func initWebRTC() {
        RTCInitializeSSL()
        peerConnectionFactory = RTCPeerConnectionFactory()

        let mandatoryConstraints = ["OfferToReceiveAudio": "true", "OfferToReceiveVideo": "false"]
        let optionalConstraints = [ "DtlsSrtpKeyAgreement": "true", "RtpDataChannels" : "true"]


        mediaConstraints = RTCMediaConstraints.init(mandatoryConstraints: mandatoryConstraints, optionalConstraints: optionalConstraints)
    }

func prepareNewConnection() -> RTCPeerConnection {
        var icsServers: [RTCIceServer] = []

        icsServers.append(RTCIceServer(urlStrings: ["stun:stun.l.google.com:19302"], username:"",credential: ""))

        let rtcConfig: RTCConfiguration = RTCConfiguration()
        rtcConfig.tcpCandidatePolicy = RTCTcpCandidatePolicy.disabled
        rtcConfig.bundlePolicy = RTCBundlePolicy.maxBundle
        rtcConfig.rtcpMuxPolicy = RTCRtcpMuxPolicy.require
        rtcConfig.iceServers = icsServers;

        peerConnection = peerConnectionFactory.peerConnection(with: rtcConfig, constraints: mediaConstraints, delegate: self)
        peerConnection.add(mediaStream);

        let tt = RTCDataChannelConfiguration();
        tt.isOrdered = false;

        tt.isNegotiated = false

        self.dataChannel = peerConnection.dataChannel(forLabel: "datachannel", configuration: tt)

        self.dataChannel.delegate = self
        print("create datachannel")

        return peerConnection;
    }

如许多人所说,我在优惠之前创建数据频道。 这种方法(见下一个代码)被多次调用。通道状态从2到3。

public func dataChannelDidChangeState(_ dataChannel: RTCDataChannel){
        print("channel.state \(dataChannel.readyState.rawValue)");
    }

但接收方需要做什么?因为什么都没有发生?我需要将数据通道绑定到接收器吗?如果是这样,我该怎么做?

1 个答案:

答案 0 :(得分:0)

从呼叫方创建数据通道并发送商品后,您应该通过从被叫方发送答案来建立对等连接。一旦建立了对等连接,一旦数据通道准备好进行数据传输,就会在被叫方侧调用peerconnection委托。

- (void)peerConnection:(RTCPeerConnection*)peerConnection
didOpenDataChannel:(RTCDataChannel*)dataChannel

要检查peerconnection是否成功建立,可以使用以下peerconnection委托检查ICE连接状态:

- (void)peerConnection:(RTCPeerConnection *)peerConnection
didChangeIceConnectionState:(RTCIceConnectionState)newState 

因此,如果newState == RTCIceConnectionStateConnected,则表示已完成对等连接,您应该调用didOpenDataChannel。