我曾尝试在Android上实施datachannel。我使用datachannel成功地将数据从android发送到web。
但是,每当我尝试将数据从网络发送到android时,android都不会收到数据,并且onMessage()永远不会被触发。
我不明白为什么会这样。以下是我实现DataChannel.Observer的方法。
private class DcObserver implements DataChannel.Observer {
// removed other overrided messages for clarity
@Override
public void onMessage(DataChannel.Buffer buffer) {
Toast.makeText(getApplicationContext(),
"Some Data has been received", Toast.LENGTH_SHORT)
.show();
Log.d("Data", "Some Data has been received");
}
}
我为每个PeerConnection对象创建对象。我有这个包含PeerConnection对象的类。
private class FilePeer implements SdpObserver {
private PeerConnection pc;
private DataChannel dc;
// removed other overrided methods for clarity
public FilePeer() {
PcObserver pcObserver = new PcObserver();
pc = factory.createPeerConnection(RTCConfig.getIceServer(),
RTCConfig.getMediaConstraints(), pcObserver);
dc = pc.createDataChannel("sendDataChannel", new DataChannel.Init());
//DcObserver dcObserver = new DcObserver();
//dc.registerObserver(dcObserver); // This one crashes the app, therefore, getting the datachannel using onDataChannel
}
}
这就是PcObserver类的样子。
private class PcObserver implements PeerConnection.Observer{
@Override
public void onDataChannel(final DataChannel dataChannel) {
runOnUiThread(new Runnable() {
public void run() {
peer.dc = dataChannel;
DcObserver dcObserver = new DcObserver();
peer.dc.registerObserver(dcObserver);
//dataChannel.registerObserver(dcObserver);
}
});
}
// other methods are removed for clarity
}
我认为peer.dc.registerObserver(dcObserver);
我做错了但是我不知道是什么。
答案 0 :(得分:1)
我在webrtc小组找到了解决这个问题的方法。
我需要保留观察者的引用,以确保在DataChannel回调时它不会被破坏。
还有一件事,我们需要删除peer.dc = dataChannel;
内的onDataChannel();
,
以下代码现在可以正常使用:
public void onDataChannel(final DataChannel dataChannel) {
final DataChannel dc = dataChannel;
runOnUiThread(new Runnable() {
public void run() {
DcObserver dcObserver = new DcObserver();
peer.dc.registerObserver(dcObserver);
}
});
}