index.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <html>
  2. <!--
  3. SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  4. SPDX-License-Identifier: MIT
  5. -->
  6. <head>
  7. <title>trickle-ice</title>
  8. </head>
  9. <body>
  10. <h3> ICE Connection States </h3>
  11. <div id="iceConnectionStates"></div> <br />
  12. <h3> Inbound DataChannel Messages </h3>
  13. <div id="inboundDataChannelMessages"></div>
  14. </body>
  15. <script>
  16. const socket = new WebSocket(`ws://${window.location.host}/websocket`)
  17. let pc = new RTCPeerConnection({
  18. iceServers: [
  19. {
  20. urls: 'stun:stun.l.google.com:19302'
  21. }
  22. ]
  23. })
  24. socket.onmessage = e => {
  25. let msg = JSON.parse(e.data)
  26. if (!msg) {
  27. return console.log('failed to parse msg')
  28. }
  29. if (msg.candidate) {
  30. pc.addIceCandidate(msg)
  31. } else {
  32. pc.setRemoteDescription(msg)
  33. }
  34. }
  35. let dc = pc.createDataChannel('data')
  36. dc.onmessage = event => {
  37. let el = document.createElement('p')
  38. el.appendChild(document.createTextNode(event.data))
  39. document.getElementById('inboundDataChannelMessages').appendChild(el);
  40. }
  41. pc.onicecandidate = e => {
  42. if (e.candidate && e.candidate.candidate !== "") {
  43. socket.send(JSON.stringify(e.candidate))
  44. }
  45. }
  46. pc.oniceconnectionstatechange = () => {
  47. let el = document.createElement('p')
  48. el.appendChild(document.createTextNode(pc.iceConnectionState))
  49. document.getElementById('iceConnectionStates').appendChild(el);
  50. }
  51. socket.onopen = () => {
  52. pc.createOffer().then(offer => {
  53. pc.setLocalDescription(offer)
  54. socket.send(JSON.stringify(offer))
  55. })
  56. }
  57. </script>
  58. </html>