Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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...
commit 5e65adaf13ea86aac78b190dc8c68f74a9b8c953 1 parent eb46e8d
@jbenet jbenet authored
Showing with 38 additions and 7 deletions.
  1. +38 −7 example/index.html
View
45 example/index.html
@@ -120,7 +120,41 @@
})
}
+
+ 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);
@@ -128,23 +162,20 @@
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));
});
Please sign in to comment.
Something went wrong with that request. Please try again.