Skip to content

Instantly share code, notes, and snippets.

@tfausak
Created September 26, 2015 13:36
Show Gist options
  • Save tfausak/d4d3b3843396052b8d5e to your computer and use it in GitHub Desktop.
Save tfausak/d4d3b3843396052b8d5e to your computer and use it in GitHub Desktop.
WebRTC data channel
<!doctype html>
<html>
<head>
<title>RTCDataChannel</title>
</head>
<body>
<p>
<a href="https://github.com/samdutton/simpl/tree/master/rtcdatachannel">
https://github.com/samdutton/simpl/tree/master/rtcdatachannel
</a>
</p>
<script>
(function () {
'use strict';
// Configuration for connections and channels.
var servers = null;
var connectionOptions = { optional: [{ RtpDataChannels: true }] };
var channelOptions = { reliable: false };
// Set up connections.
var localPeerConnection = new webkitRTCPeerConnection(servers, connectionOptions);
console.log('local peer connection', localPeerConnection);
var remotePeerConnection = new webkitRTCPeerConnection(servers, connectionOptions);
console.log('remote peer connection', remotePeerConnection);
// Handle ICE candidates.
localPeerConnection.onicecandidate = function (event) {
console.log('local ice candidate', event);
if (event.candidate) {
remotePeerConnection.addIceCandidate(event.candidate);
}
}
remotePeerConnection.onicecandidate = function (event) {
console.log('remote ice candidate', event);
if (event.candidate) {
localPeerConnection.addIceCandidate(event.candidate);
}
}
// Set up channels.
var sendChannel = localPeerConnection.createDataChannel('sendDataChannel', channelOptions);
console.log('send channel', sendChannel);
var receiveChannel;
remotePeerConnection.ondatachannel = function (event) {
console.log('remote data channel', event);
receiveChannel = event.channel;
console.log('receive channel', receiveChannel);
};
// Create a local offer and a remote answer.
localPeerConnection.createOffer(function (description) {
console.log('local offer description', description);
localPeerConnection.setLocalDescription(description);
remotePeerConnection.setRemoteDescription(description);
remotePeerConnection.createAnswer(function (d) {
console.log('remote answer description', d);
remotePeerConnection.setLocalDescription(d);
localPeerConnection.setRemoteDescription(d);
});
});
// Send some data over the channel. This has to wait for the offer to
// be accepted.
window.setTimeout(function () {
console.log('sending...');
receiveChannel.onmessage = function (event) {
console.log('received message', event);
}
sendChannel.send('test');
}, 1000);
// Close the channels and connections. This has to wait for the message
// to be sent.
window.setTimeout(function () {
console.log('closing...');
sendChannel.close();
receiveChannel.close();
localPeerConnection.close();
remotePeerConnection.close();
}, 2000);
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment