Android WebRTC DataChannel 二进制传输模式

Android WebRTC DataChannel binary transfer mode

我使用 WebRTC DataChannel 实现了在两部 android 手机之间传输数据:

一方面,我发送数据:

boolean isBinaryFile = false;
File file = new File(path); // let's assume path is a .whatever file's path (txt, jpg, pdf..) 
ByteBuffer byteBuffer = ByteBuffer.wrap(convertFileToByteArray(file));
DataChannel.Buffer buf = new DataChannel.Buffer(byteBuffer, isBinaryFile); 
dataChannel.send(buf);

另一方面,无论 isBinaryFile 值如何,都应调用此回调:

public void onMessage( final DataChannel.Buffer buffer ){
    Log.e(TAG, "Incomming file on DataChannel");

    ByteBuffer data = buffer.data;
    byte[] bytes = new byte[ data.capacity() ];
    data.get(bytes);

    // If it's not a binary file (text)
    if( !buffer.binary ) {
        String strData = new String( bytes );
        Log.e(TAG, "Text file is : " + strData);
    } else {
        Log.e(TAG, "Received binary file ! :)");
    }
}

对于任何文件,当 isBinaryFilefalse 时,将调用回调,我能够打印文本,甚至重建文件(图片、pdf 等)。

isBinaryFiletrue 时,出现以下错误:

Warning(rtpdataengine.cc:317): Not sending data because binary type is unsupported.

看完this,看来我需要用SCTP DataChannels,但我不知道怎么用!

终于找到解决办法了!

之前,我用 RtpDataChannels 约束构造了我的 PeerConnection true;但要使用 SCTP DataChannels,您必须将其设置为默认值(或将其设置为 false),如下所示:

MediaConstraints pcConstraints = signalingParameters.pcConstraints;
// pcConstraints.optional.add(new KeyValuePair("RtpDataChannels", "false"));
pcConstraints.optional.add(new KeyValuePair("DtlsSrtpKeyAgreement", "true"));
pc = factory.createPeerConnection(signalingParameters.iceServers,
            pcConstraints, pcObserver);

简单! :-)