script.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. (function (){
  2. console.log('Hello');
  3. const connectButton = document.getElementById('createConnectionBtn')
  4. connectButton.addEventListener('click', createConnection, false)
  5. })();
  6. function createConnection() {
  7. const localConnection = new RTCPeerConnection();
  8. const sendChannel = localConnection.createDataChannel('channel');
  9. console.dir(sendChannel);
  10. sendChannel.onopen = e => {
  11. console.log('open')
  12. console.log(e)
  13. }
  14. sendChannel.onclose = e => {
  15. console.log('close')
  16. console.log(e)
  17. }
  18. const connectionInfo = {};
  19. localConnection.onicecandidate = e => {
  20. if (e.candidate) {
  21. const candidate = e.candidate.candidate;
  22. connectionInfo.candidate = candidate;
  23. document.body.append(JSON.stringify(connectionInfo));
  24. }
  25. }
  26. localConnection.onicecandidateerror = err => {
  27. console.log(err)
  28. }
  29. localConnection.createOffer().then((desc) => {
  30. connectionInfo.description = desc.sdp;
  31. localConnection.setLocalDescription(desc);
  32. }
  33. )
  34. const connectRemote = document.getElementById('connectRemote')
  35. function createRemoteConnection() {
  36. const remoteDescText = document.getElementById('remoteDesc').value
  37. const remoteDescJSON = JSON.parse(remoteDescText);
  38. const remoteDesc = {
  39. type: "answer",
  40. sdp: remoteDescJSON.description
  41. }
  42. const remoteCandidate = {
  43. candidate: remoteDescJSON.candidate,
  44. sdpMid: "0", // Media stream ID for audio
  45. sdpMLineIndex: 0 // Something to do with media
  46. }
  47. console.dir(remoteDescJSON)
  48. localConnection.setRemoteDescription(remoteDesc).then((e) => {
  49. console.log(e)
  50. });
  51. }
  52. connectRemote.addEventListener('click', createRemoteConnection, false)
  53. const sendButton = document.getElementById('sendDataBtn')
  54. sendButton.addEventListener('click', sendMessage, false)
  55. function sendMessage() {
  56. const messageText = document.getElementById('sendData').value;
  57. sendChannel.send(messageText);
  58. }
  59. }