Skip to content

Instantly share code, notes, and snippets.

@Yogu
Created September 30, 2014 12:02
Show Gist options
  • Save Yogu/fa7ea5ab91c6134a02d0 to your computer and use it in GitHub Desktop.
Save Yogu/fa7ea5ab91c6134a02d0 to your computer and use it in GitHub Desktop.
Simple RTCDataChannel setup
var RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
var RTCSessionDescription = window.mozRTCSessionDescription || window.webkitRTCSessionDescription || window.RTCSessionDescription;
var RTCIceCandidate = window.mozRTCIceCandidate || window.webkitRTCIceCandidate || window.RTCIceCandidate;
var RTC_CONFIGURATION = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
var MEDIA_CONSTRAINTS = {optional: [{internalSctpDataChannels: true},{DtlsSrtpKeyAgreement: true}]};
function errorCallback(error) {
console.log(error);
}
var rtc1 = new RTCPeerConnection(RTC_CONFIGURATION, MEDIA_CONSTRAINTS);
var rtc2 = new RTCPeerConnection(RTC_CONFIGURATION, MEDIA_CONSTRAINTS);
rtc1.onicecandidate = function(e) {
if (!e.candidate) return;
console.log('candidate1');
rtc2.addIceCandidate(e.candidate);
};
rtc2.onicecandidate = function(e) {
console.log(e.candidate);
if (!e.candidate) return;
console.log('candidate2');
rtc1.addIceCandidate(e.candidate);
};
rtc1.onnegotiationneeded = function() {
console.log('onnegotiationneeded');
rtc1.createOffer(function(desc1) {
console.log('created desc1');
rtc1.setLocalDescription(desc1, function() {
console.log('set rtc1.local');
rtc2.setRemoteDescription(desc1, function() {
console.log('set rtc2.remote');
rtc2.createAnswer(function(desc2) {
console.log('created desc2');
rtc2.setLocalDescription(desc2, function() {
console.log('set rtc2,local');
rtc1.setRemoteDescription(desc2, function() {
console.log('set rtc1.remote');
}, errorCallback);
});
}, errorCallback);
}, errorCallback);
}, errorCallback);
}, errorCallback);
};
rtc2.ondatachannel = function(e) {
var dc2 = e.channel;
window.dc2 = dc2;
dc2.onerror = errorCallback;
console.log('rtc2 received datachannel');
dc2.onopen = function() {
console.log('open2');
};
dc2.onmessage = function(e) {
console.log(e);
};
};
var dc1 = rtc1.createDataChannel('data');
dc1.onerror = errorCallback;
dc1.onopen = function() {
console.log('open1');
dc1.send('hi');
};
window.rtc1 = rtc1; window.rtc2 = rtc2; window.dc1 = dc1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment