webrtc学习笔记二(datachannel)

https://www.webrtc-experiment.com/DataChannel/
https://www.npmjs.com/package/datachannel.io
datachannel.io
官方:
http://www.html5rocks.com/en/tutorials/webrtc/datachannels/?redirect_from_locale=zh


本地调用的传数据的datachannel

<!DOCTYPE html>
<html>
<head><title>RTCDataChannel</title></head>
<body>
<button id="startButton" onclick="createConnection()">Start</button>
<button id="sendButton" onclick="sendData()">Send</button>
<button id="closeButton" onclick="closeDataChannels()">Stop</button>
<textarea id="dataChannelSend" >abc</textarea>
<textarea id="dataChannelReceive" ></textarea>
<script type="text/javascript">
var localPeerConnection, remotePeerConnection;//用于peer跟peer之间呼叫和建立连接以便传输音视频数据流
var sendChannel, receiveChannel;//用于peer跟peer之间传输音视频之外的一般数据。

function trace(text) {
console.log((window.performance.now() / 1000).toFixed(3) + ': ' + text);
}

function createConnection() {
var servers = null;
localPeerConnection = window.localPeerConnection =new webkitRTCPeerConnection(servers,{optional: [{RtpDataChannels: true}]});
remotePeerConnection = window.remotePeerConnection = new webkitRTCPeerConnection(servers,{optional: [{RtpDataChannels: true}]});
try {
sendChannel = localPeerConnection.createDataChannel('sendDataChannel',{reliable: false});
} catch (e) {
alert('createDataChannel() failed with exception: ' + e.message);
}
localPeerConnection.onicecandidate = function(event) {
if (event.candidate) {
remotePeerConnection.addIceCandidate(event.candidate);
trace('★★★★★Local ICE candidate: \n' + event.candidate.candidate);
}
}
remotePeerConnection.onicecandidate = function(event) {
if (event.candidate) {
localPeerConnection.addIceCandidate(event.candidate);
trace('★★★Remote ICE candidate: \n ' + event.candidate.candidate);
}
};

sendChannel.onopen = trace('--Send channel open state is : ' +sendChannel.readyState);;
sendChannel.onclose = trace('--Send channel close state is: ' +sendChannel.readyState);;

remotePeerConnection.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event) {
document.getElementById('dataChannelReceive').value = event.data;
};
receiveChannel.onopen = trace('--Receive channel open state is: ' + receiveChannel.readyState);;
receiveChannel.onclose = trace('--Receive channel close state is: ' + receiveChannel.readyState);;
};

localPeerConnection.createOffer(gotLocalDescription);//
}

function sendData() {
var data = document.getElementById('dataChannelSend').value;
sendChannel.send(data);
}

function closeDataChannels() {
console.log("------close");
sendChannel.close();
receiveChannel.close();
localPeerConnection.close();
remotePeerConnection.close();
localPeerConnection = null;
remotePeerConnection = null;
}

function gotLocalDescription(desc) {
trace("createOffer gotLocalDescription--->");
localPeerConnection.setLocalDescription(desc);
// trace('------|||||----Offer from localPeerConnection \n' + desc.sdp);
remotePeerConnection.setRemoteDescription(desc);
remotePeerConnection.createAnswer(gotRemoteDescription);//
}

function gotRemoteDescription(desc) {
trace("createAnswer gotRemoteDescription--->");
remotePeerConnection.setLocalDescription(desc);
//trace('------------->>>>>>>>>>>>Answer from remotePeerConnection \n' + desc.sdp);
localPeerConnection.setRemoteDescription(desc);
}
</script>

</body>
</html>

### WebRTC DataChannel 使用指南 WebRTC (Web Real-Time Communication) 提供了一种通过浏览器实现实时通信的方法。DataChannelWebRTC 中的一个重要特性,允许两个对等端之间传输任意数据[^3]。 #### 创建并配置 PeerConnection 对象 为了建立 DataChannel 连接,首先需要创建 RTCPeerConnection 实例: ```javascript const configuration = { iceServers: [ { urls: 'stun:stun.l.google.com:19302' } ] }; let peerConnection = new RTCPeerConnection(configuration); ``` #### 打开 DataChannel 并设置回调函数 接下来可以打开一个新的 DataChannel,并指定其标签以及一些可选参数: ```javascript // 建立 data channel let sendChannel = peerConnection.createDataChannel('sendDataChannel', { ordered: false, // 是否保持消息顺序,默认 true }); // 设置接收消息事件处理程序 sendChannel.onmessage = function(event){ console.log(`Received message from remote side: ${event.data}`); }; // 当通道状态改变时触发此事件处理器 sendChannel.onopen = () => console.log('Send Channel has been opened'); sendChannel.onclose = () => console.log('Send Channel is closed'); ``` #### 发送与接收数据 一旦连接成功建立并且 DataChannel 处于 open 状态,则可以通过 `send()` 方法发送字符串或 Blob 数据给对方;而另一方则会收到这些信息作为 MessageEvent 的一部分,在上面的例子中已经定义好了如何响应这种类型的事件。 对于进制文件(如图片),应该先将其转换成 ArrayBuffer 或者 Blob 形式再传递过去: ```javascript function sendMessage(message) { if(sendChannel.readyState === "open") { sendChannel.send(message); console.log(`Sent message to remote side: ${message}`); } else { console.error("Failed to send message because the connection is not ready"); } } ``` #### 关闭 DataChannel 和清理资源 当不再需要使用某个特定的数据流时,应当调用 close() 来关闭它,并断开整个 RTCPeerConnection 以释放占用的网络接口和其他系统资源。 ```javascript if (sendChannel && sendChannel.readyState !== "closed"){ sendChannel.close(); } peerConnection.close(); console.log("Closed all connections and channels."); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值