Browse files

DataChannel support (with fallback)

This commit adds support for the WebRTC DataChannel API.
If available, it sends all chat messages through DataChannel.
If not, it falls back to using the websocket.
  • Loading branch information...
1 parent eb46e8d commit 5e65adaf13ea86aac78b190dc8c68f74a9b8c953 @jbenet jbenet committed Jan 27, 2013
Showing with 38 additions and 7 deletions.
  1. +38 −7 example/index.html
View
45 example/index.html
@@ -120,31 +120,62 @@
})
}
+
+ var websocketChat = {
+ send: function (message) {
+ rtc._socket.send(message);
+ },
+ recv: function (message) {
+ return message;
+ },
+ event: 'receive_chat_msg',
+ };
+
+ var dataChannelChat = {
+ send: function (message) {
+ for (var connection in rtc.dataChannels) {
+ var channel = rtc.dataChannels[connection];
+ channel.send(message);
+ }
+ },
+ recv: function (channel, message) {
+ return JSON.parse(message).data;
+ },
+ event: 'data stream data',
+ };
+
function initChat() {
+ var chat;
+
+ if (rtc.dataChannelSupport) {
+ console.log('initializing data channel chat');
+ chat = dataChannelChat;
+ } else {
+ console.log('initializing websocket chat');
+ chat = websocketChat;
+ }
+
var input = document.getElementById("chatinput");
var room = window.location.hash.slice(1);
var color = "#"+((1<<24)*Math.random()|0).toString(16);
input.addEventListener('keydown', function(event) {
var key = event.which || event.keyCode;
if (key === 13) {
- rtc._socket.send(JSON.stringify({
+ chat.send(JSON.stringify({
"eventName": "chat_msg",
"data": {
"messages": input.value,
"room": room,
"color": color
}
- }), function(error) {
- if (error) {
- console.log(error);
- }
- });
+ }));
addToChat(input.value);
input.value = "";
}
}, false);
- rtc.on('receive_chat_msg', function(data) {
+ rtc.on(chat.event, function() {
+ data = chat.recv.apply(this, arguments);
console.log(data.color);
addToChat(data.messages, data.color.toString(16));
});

0 comments on commit 5e65ada

Please sign in to comment.