script.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /*
  2. * libdatachannel example web client
  3. * Copyright (C) 2020 Lara Mackey
  4. * Copyright (C) 2020 Paul-Louis Ageneau
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. window.addEventListener('load', () => {
  20. const config = {
  21. iceServers: [{
  22. urls: 'stun:stun.l.google.com:19302', // change to your STUN server
  23. }],
  24. };
  25. const localId = randomId(8);
  26. const url = `ws://localhost:8000/${localId}`;
  27. const peerConnectionMap = {};
  28. const dataChannelMap = {};
  29. const offerId = document.getElementById('offerId');
  30. const offerBtn = document.getElementById('offerBtn');
  31. const sendMsg = document.getElementById('sendMsg');
  32. const sendBtn = document.getElementById('sendBtn');
  33. const _localId = document.getElementById('localId');
  34. _localId.textContent = localId;
  35. console.log('Connecting to signaling...');
  36. openSignaling(url)
  37. .then((ws) => {
  38. console.log('WebSocket connected, signaling ready');
  39. offerId.disabled = false;
  40. offerBtn.disabled = false;
  41. offerBtn.onclick = () => offerPeerConnection(ws, offerId.value);
  42. })
  43. .catch((err) => console.error(err));
  44. function openSignaling(url) {
  45. return new Promise((resolve, reject) => {
  46. const ws = new WebSocket(url);
  47. ws.onopen = () => resolve(ws);
  48. ws.onerror = () => reject(new Error('WebSocket error'));
  49. ws.onclosed = () => console.error('WebSocket disconnected');
  50. ws.onmessage = (e) => {
  51. if(typeof(e.data) != 'string') return;
  52. const message = JSON.parse(e.data);
  53. const { id, type } = message;
  54. let pc = peerConnectionMap[id];
  55. if(!pc) {
  56. if(type != 'offer') return;
  57. // Create PeerConnection for answer
  58. console.log(`Answering to ${id}`);
  59. pc = createPeerConnection(ws, id);
  60. }
  61. switch(type) {
  62. case 'offer':
  63. case 'answer':
  64. pc.setRemoteDescription({
  65. sdp: message.description,
  66. type: message.type,
  67. })
  68. .then(() => {
  69. if(type == 'offer') {
  70. // Send answer
  71. sendLocalDescription(ws, id, pc, 'answer');
  72. }
  73. });
  74. break;
  75. case 'candidate':
  76. pc.addIceCandidate({
  77. candidate: message.candidate,
  78. sdpMid: message.mid,
  79. });
  80. break;
  81. }
  82. }
  83. });
  84. }
  85. function offerPeerConnection(ws, id) {
  86. // Create PeerConnection
  87. console.log(`Offering to ${id}`);
  88. pc = createPeerConnection(ws, id);
  89. // Create DataChannel
  90. const label = "test";
  91. console.log(`Creating DataChannel with label "${label}"`);
  92. const dc = pc.createDataChannel(label);
  93. setupDataChannel(dc, id);
  94. // Send offer
  95. sendLocalDescription(ws, id, pc, 'offer');
  96. }
  97. // Create and setup a PeerConnection
  98. function createPeerConnection(ws, id) {
  99. const pc = new RTCPeerConnection(config);
  100. pc.onconnectionstatechange = () => console.log(`Connection state: ${pc.connectionState}`);
  101. pc.onicegatheringstatechange = () => console.log(`Gathering state: ${pc.iceGatheringState}`);
  102. pc.onicecandidate = (e) => {
  103. if (e.candidate) {
  104. // Send candidate
  105. sendLocalCandidate(ws, id, e.candidate);
  106. }
  107. };
  108. pc.ondatachannel = (e) => {
  109. const dc = e.channel;
  110. console.log(`"DataChannel from ${id} received with label "${dc.label}"`);
  111. setupDataChannel(dc, id);
  112. dc.send(`Hello from ${localId}`);
  113. sendMsg.disabled = false;
  114. sendBtn.disabled = false;
  115. sendBtn.onclick = () => dc.send(sendMsg.value);
  116. };
  117. peerConnectionMap[id] = pc;
  118. return pc;
  119. }
  120. // Setup a DataChannel
  121. function setupDataChannel(dc, id) {
  122. dc.onopen = () => {
  123. console.log(`DataChannel from ${id} open`);
  124. sendMsg.disabled = false;
  125. sendBtn.disabled = false;
  126. sendBtn.onclick = () => dc.send(sendMsg.value);
  127. };
  128. dc.onclose = () => {
  129. console.log(`DataChannel from ${id} closed`);
  130. };
  131. dc.onmessage = (e) => {
  132. if(typeof(e.data) != 'string') return;
  133. console.log(`Message from ${id} received: ${e.data}`);
  134. document.body.appendChild(document.createTextNode(e.data));
  135. };
  136. dataChannelMap[id] = dc;
  137. return dc;
  138. }
  139. function sendLocalDescription(ws, id, pc, type) {
  140. (type == 'offer' ? pc.createOffer() : pc.createAnswer())
  141. .then((desc) => pc.setLocalDescription(desc))
  142. .then(() => {
  143. const { sdp, type } = pc.localDescription;
  144. ws.send(JSON.stringify({
  145. id,
  146. type,
  147. description: sdp,
  148. }));
  149. });
  150. }
  151. function sendLocalCandidate(ws, id, cand) {
  152. const {candidate, sdpMid} = cand;
  153. ws.send(JSON.stringify({
  154. id,
  155. type: 'candidate',
  156. candidate,
  157. mid: sdpMid,
  158. }));
  159. }
  160. // Helper function to generate a random ID
  161. function randomId(length) {
  162. const characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  163. const pickRandom = () => characters.charAt(Math.floor(Math.random() * characters.length));
  164. return [...Array(length)].map(pickRandom).join('');
  165. }
  166. });