我实现了使用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);
很简单! :-)