If you're new to WebRTC; please read this document.
|
Here is a simple one-page chat demo uses RTCDataChannel APIs. View Source Code
|
First of all, you need to reference this js-wrapper file for RTCWeb APIs:
<script src="https://www.webrtc-experiment.com/RTCPeerConnection-v1.5.js"></script>
|
You JUST need to write below code! Your project will work fine on Firefox Aurora/Nightly and Chrome Canary!
|
Offerer
|
You need to use offer/answer model to exchange SDP/ICE. For "offerer": use code like this:
var peer = RTCPeerConnection({
onICE: function (candidate) {},
onOfferSDP: function(sdp) {},
onChannelMessage: function(event) {
},
onChannelOpened: function(channel) {
window.channel = channel;
}
});
Here is the short explanation of above code ↑
-
onICE: It returns locally generated ICE candidates; so you can share them with other peer(s).
candidate object contains two properties:
- candidate.
sdpMLineIndex
- candidate.
candidate
-
onOfferSDP: returns offer sdp; so you can send it to other peer to get answer sdp.
-
onChannelMessage : The message sent by other peer/channel.
-
onChannelOpened : On data channel gets ready. It returns channel object.
You can send messages like this:
channel.send('');
channel.send(
JSON.stringify({ message: "" })
);
peer.sendData('');
peer.sendData(
JSON.stringify({ message: "" })
);
Some extra options:
var peer = RTCPeerConnection({
...
onChannelClosed : function(event) {},
onChannelError : function(event) {},
channel : 'ABCDEF',
optional : { optional: [{ RtpDataChannels: true}] }
});
By default optional value is "{ optional: [{ RtpDataChannels: true}] } " --- so you don't need to change it.
You don't need to attach client stream. You JUST need to exchange SDP/ICE and that's all you need to do!!
YOU can use WebSocket or XHR for SDP/ICE exchange.
|
On Getting Answer SDP:
|
Now assume that other peer generated answer sdp and sent to you; you can pass that sdp to this function:
peer.addAnswerSDP( answer_sdp );
|
On Getting ICE:
|
Now assume that other peer generated ICE and sent to you; you can pass that ICE to this function:
peer.addICE({
sdpMLineIndex : candidate.sdpMLineIndex,
candidate : candidate.candidate
});
|
Answerer
|
99% process is the same for peer who "creates answer sdp"; the only difference is: for that peer you don't need "onOfferSDP " and also you don't need to call "peer.addAnswerSDP( answer_sdp ); ". What extra you need to do is here:
var peer = RTCPeerConnection({
offerSDP : offer_sdp,
onAnswerSDP : function(sdp) {},
onICE : function (candidate) {},
onChannelMessage : function(event) {
},
onChannelOpened : function(channel) {}
});
Let me elaborate:
-
offerSDP: you need to pass offer sdp sent by other peer (offerer).
-
onAnswerSDP: returns answer sdp so you can send it to other peer (offerer).
|
Note: For a detailed document about "How to write a realtime WebRTC app using socket.io or WebSocket?" click here.
|
Are you interested in a "simple" guide about RTCDataChannel? Read this document.
|