Skip to content

Commit 5e65ada

Browse files
committed
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.
1 parent eb46e8d commit 5e65ada

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

example/index.html

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -120,31 +120,62 @@
120120
})
121121
}
122122

123+
124+
var websocketChat = {
125+
send: function (message) {
126+
rtc._socket.send(message);
127+
},
128+
recv: function (message) {
129+
return message;
130+
},
131+
event: 'receive_chat_msg',
132+
};
133+
134+
var dataChannelChat = {
135+
send: function (message) {
136+
for (var connection in rtc.dataChannels) {
137+
var channel = rtc.dataChannels[connection];
138+
channel.send(message);
139+
}
140+
},
141+
recv: function (channel, message) {
142+
return JSON.parse(message).data;
143+
},
144+
event: 'data stream data',
145+
};
146+
123147
function initChat() {
148+
var chat;
149+
150+
if (rtc.dataChannelSupport) {
151+
console.log('initializing data channel chat');
152+
chat = dataChannelChat;
153+
} else {
154+
console.log('initializing websocket chat');
155+
chat = websocketChat;
156+
}
157+
124158
var input = document.getElementById("chatinput");
125159
var room = window.location.hash.slice(1);
126160
var color = "#"+((1<<24)*Math.random()|0).toString(16);
127161

128162
input.addEventListener('keydown', function(event) {
129163
var key = event.which || event.keyCode;
130164
if (key === 13) {
131-
rtc._socket.send(JSON.stringify({
165+
chat.send(JSON.stringify({
132166
"eventName": "chat_msg",
133167
"data": {
134168
"messages": input.value,
135169
"room": room,
136170
"color": color
137171
}
138-
}), function(error) {
139-
if (error) {
140-
console.log(error);
141-
}
142-
});
172+
}));
143173
addToChat(input.value);
144174
input.value = "";
145175
}
146176
}, false);
147-
rtc.on('receive_chat_msg', function(data) {
177+
rtc.on(chat.event, function() {
178+
data = chat.recv.apply(this, arguments);
148179
console.log(data.color);
149180
addToChat(data.messages, data.color.toString(16));
150181
});

0 commit comments

Comments
 (0)