在Webrtc中,想要实现文本消息,刚开始我想的是直接能过socket.io进行消息发送,这个理论上没有什么问题,后面搜索了一下,发现webrtc还提供了一个数据通道:DataChannel
使用流程
1、首先创建DataChannel
private void createDateChannel(){
DataChannel.Init init=new DataChannel.Init();
init.ordered=true;
init.negotiated=true;
init.maxRetransmits=-1;
init.maxRetransmitTimeMs=-1;
init.id=0;
dc = pc.createDataChannel("sendDataChannel", init);
}
注:pc即PeerConnection
2、给DataChannel添加数据监听器:
dc.registerObserver(new DataChannel.Observer() {
@Override
public void onBufferedAmountChange(long l) {
Log.d(TAG,"DataChannel onBufferedAmountChange: ");
}
@Override
public void onStateChange() {
Log.d(TAG,"DataChannel onStateChange: ");
}
@Override
public void onMessage(DataChannel.Buffer buffer) {
Log.d(TAG,"DataChannel onMessage: "+ DataUtil.getString(buffer.data));
}
});
收到消息会触发onMessage方法。
3、发送消息
public void sengMsg(String str){
DataChannel.Buffer buffer = new DataChannel.Buffer(DataUtil.getByteBuffer(str),false);
dc.send(buffer);
}
4、用完后取消注册监听器
dc.unregisterObserver();
5、附上面上面DataUtil的源码
public class DataUtil {
public static ByteBuffer getByteBuffer(String str) {
return ByteBuffer.wrap(str.getBytes());
}
public static String getString(ByteBuffer buffer) {
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
try {
charset = Charset.forName("UTF-8");
decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
return charBuffer.toString();
} catch (Exception ex) {
ex.printStackTrace();
return "error";
}
}
}
|