bsu*_*ire 5 javascript real-time webrtc rtcdatachannel
我正在尝试使用 WebRTC 设置对等文件共享系统。我可以在每一侧打开一个数据通道,但我无法从一个用户向另一个用户发送消息。此外,如果一个对等方关闭通道,另一个对等方,则仅针对该用户触发 onclose 事件。
通过 webRTC 设置和使用数据通道的正确方法是什么?
你能告诉我我的代码有什么问题或缺失吗?
//create RTC peer objet.
var RTCPeerConnection = webkitRTCPeerConnection;
var RTCIceCandidate = window.RTCIceCandidate;
var RTCSessionDescription = window.RTCSessionDescription;
var iceServers = {
iceServers: [{
url: 'stun:stun.l.google.com:19302'
}]
};
var p2p_connection = new RTCPeerConnection({
iceServers: [
{ 'url': (IS_CHROME ? 'stun:stun.l.google.com:19302' : 'stun:23.21.150.121') }
]
});
// send offer (only executes in one browser)
function initiateConnection() {
p2p_connection.createOffer(function (description) {
p2p_connection.setLocalDescription(description);
server_socket.emit('p2p request', description,my_username);
});
};
// receive offer and send answer
server_socket.on('p2p request', function(description,sender){
console.log('received p2p request');
p2p_connection.setRemoteDescription(new RTCSessionDescription(description));
p2p_connection.createAnswer(function (description) {
p2p_connection.setLocalDescription(description);
server_socket.emit('p2p reply', description,sender);
});
});
// receive answer
server_socket.on('p2p reply', function(description,sender){
console.log('received p2p reply');
p2p_connection.setRemoteDescription(new RTCSessionDescription(description));
});
// ICE candidates
p2p_connection.onicecandidate = onicecandidate; // sent event listener
// locally generated
function onicecandidate(event) {
if (!p2p_connection || !event || !event.candidate) return;
var candidate = event.candidate;
server_socket.emit('add candidate',candidate,my_username);
}
// sent by other peer
server_socket.on('add candidate', function(candidate,my_username){
p2p_connection.addIceCandidate(new RTCIceCandidate({
sdpMLineIndex: candidate.sdpMLineIndex,
candidate: candidate.candidate
}));
});
// data channel
var dataChannel = p2p_connection.createDataChannel('label');
dataChannel.onmessage = function (event) {
var data = event.data;
console.log("I got data channel message: ", data);
};
dataChannel.onopen = function (event) {
console.log("Data channel ready");
dataChannel.send("Hello World!");
};
dataChannel.onclose = function (event) {
console.log("Data channel closed.");
};
dataChannel.onerror = function (event) {
console.log("Data channel error!");
}
Run Code Online (Sandbox Code Playgroud)
更新:
在那里找到解决方案:http : //www.html5rocks.com/en/tutorials/webrtc/basics/
p2p_connection.ondatachannel = function (event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event){
console.log(event.data);
};
};
Run Code Online (Sandbox Code Playgroud)
您可能会考虑使用该simple-peer库来避免将来处理这些复杂性。WebRTC API 调用很混乱,有时很难正确排序。
simple-peer支持视频/语音流、数据通道(文本和二进制数据),您甚至可以将数据通道用作node.js样式的双工流。它还支持高级选项,例如禁用滴流 ICE 候选者(因此每个客户端只需发送一条提供/应答消息,而不是许多重复的 ICE 候选者消息)。它不固执,适用于任何后端。
https://github.com/feross/simple-peer