1

我试图在 Android 上实现数据通道。我使用数据通道成功地将数据从 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);但我不知道是什么。

4

1 回答 1

1

我在 webrtc group 上找到了这个问题的解决方案。

我需要保留观察者的引用,以确保在 DataChannel 回调时它不会被破坏。

还有一件事,我们需要做的是删除peer.dc = dataChannel;inside 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);

              }
            });


    }
于 2015-04-18T12:28:36.587 回答