webrtc同样适用于非音视频数据传输
<Callout type="info"> 参考mdn文档:<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Using_data_channels">WebRTC data channels</a> </Callout>
createdatachannel
js
pc.createDataChannel("xxx").then(res => {
// ...
})
参数及配置
- label 一个便于理解的通道名. 该字符串不能长于 65,535 字节.
- options
- ordered
- maxPacketLifeTime(包的最大存活时间) / maxRetransmits(尝试的最大次数)
- negotiated
- 如果为false,一段使用createDataChannel创建通道,另一段监听ondatachannel事件
- 如果为true,两端都可以调用createDataChannel创建通道,通过id来表示同一通道
datachannel事件
- onmessage
- onopen
- onclose
- onerror
非音视频传输方式
| TCP | UDP | SCTP | |
|---|---|---|---|
| Reliability | reliable | unreliable | configurable |
| Delivery | orderd | unordered | configurable |
| Transmission | byte-oriented | message-oriented | message-oriented |
| Flow control | yes | no | yes |
| Congstion control | yes | no | yes |
文本传输demo
js
dc = pc.createDataChannel('chatchannel');
dc.onmessage = function receivemsg(e){
var msg = e.data;
if(msg){
console.log(msg);
}else{
console.error('received msg is null');
}
};
dc.onopen = noop => noop;
dc.onclose = noop => noop;