Android WebRTC DataChannel binary transfer mode

2020-07-29 22:50发布

I achieved to transfer data between two android phones using WebRTC's DataChannel :

On one side, I send the data:

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);

On the other side, this callback should be called regardless of isBinaryFile value :

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 ! :)");
    }
}

In the case of any file, when isBinaryFile is false, the callback is called and I'm able to print the text, or even reconstruct the file (images, pdf, whatever).

When isBinaryFile is true I get the following error:

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

After reading this, looks like I need to use SCTP DataChannels, but I don't know how !

1条回答
混吃等死
2楼-- · 2020-07-29 23:39

Finally found a solution !

Before, I constructed my PeerConnection with RtpDataChannels constraint to true; but to use SCTP DataChannels, you must let it to default (or set it to false), like this:

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);

Simple ! :-)

查看更多
登录 后发表回答