我实现了使用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 ! :)");
    }
}


对于任何文件,当isBinaryFile为false时,将调用回调,并且我能够打印文本,甚至重建文件(图像,pdf等)。

isBinaryFile为true时,出现以下错误:

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


阅读this后,看起来我需要使用SCTP DataChannels,但是我不知道如何!

最佳答案

终于找到了解决方案!

之前,我以PeerConnection约束构造了RtpDataChannels。但是要使用SCTP DataChannel,必须将其设置为默认值(或将其设置为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);


很简单! :-)

08-17 13:25