script.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. const answererUrl = 'http://localhost:8000/answerer.html?connection=' + btoa(JSON.stringify(connectionInfo));
  24. const createLink = document.createElement('a');
  25. createLink.setAttribute('href', answererUrl);
  26. createLink.setAttribute('target', 'new');
  27. createLink.append('Open me ;)');
  28. document.body.append(createLink);
  29. }
  30. }
  31. localConnection.onicecandidateerror = err => {
  32. console.log(err)
  33. }
  34. localConnection.createOffer().then((desc) => {
  35. connectionInfo.description = desc.sdp;
  36. localConnection.setLocalDescription(desc);
  37. }
  38. )
  39. const connectRemote = document.getElementById('connectRemote')
  40. function createRemoteConnection() {
  41. const remoteDescText = document.getElementById('remoteDesc').value
  42. const remoteDescJSON = JSON.parse(remoteDescText);
  43. const remoteDesc = {
  44. type: "answer",
  45. sdp: remoteDescJSON.description
  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. }