|
120 | 120 | })
|
121 | 121 | }
|
122 | 122 |
|
| 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 | + |
123 | 147 | 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 | + |
124 | 158 | var input = document.getElementById("chatinput");
|
125 | 159 | var room = window.location.hash.slice(1);
|
126 | 160 | var color = "#"+((1<<24)*Math.random()|0).toString(16);
|
127 | 161 |
|
128 | 162 | input.addEventListener('keydown', function(event) {
|
129 | 163 | var key = event.which || event.keyCode;
|
130 | 164 | if (key === 13) {
|
131 |
| - rtc._socket.send(JSON.stringify({ |
| 165 | + chat.send(JSON.stringify({ |
132 | 166 | "eventName": "chat_msg",
|
133 | 167 | "data": {
|
134 | 168 | "messages": input.value,
|
135 | 169 | "room": room,
|
136 | 170 | "color": color
|
137 | 171 | }
|
138 |
| - }), function(error) { |
139 |
| - if (error) { |
140 |
| - console.log(error); |
141 |
| - } |
142 |
| - }); |
| 172 | + })); |
143 | 173 | addToChat(input.value);
|
144 | 174 | input.value = "";
|
145 | 175 | }
|
146 | 176 | }, false);
|
147 |
| - rtc.on('receive_chat_msg', function(data) { |
| 177 | + rtc.on(chat.event, function() { |
| 178 | + data = chat.recv.apply(this, arguments); |
148 | 179 | console.log(data.color);
|
149 | 180 | addToChat(data.messages, data.color.toString(16));
|
150 | 181 | });
|
|
0 commit comments