script.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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:8080/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. const pollForConnection = setInterval(() => {
  30. fetch(
  31. 'http://localhost:8000/state/json'
  32. ).then(response => {
  33. if (response.status !== 200) {
  34. throw new Error('bad status ' + response.status);
  35. }
  36. return response.json();
  37. }).then(data => {
  38. if (data.description) {
  39. console.log('yes');
  40. clearInterval(pollForConnection);
  41. createRemoteConnection(data.description);
  42. }
  43. else {
  44. console.log('no');
  45. }
  46. })
  47. }, 5000)
  48. }
  49. }
  50. localConnection.onicecandidateerror = err => {
  51. console.log(err)
  52. }
  53. localConnection.createOffer().then((desc) => {
  54. connectionInfo.description = desc.sdp;
  55. localConnection.setLocalDescription(desc);
  56. }
  57. )
  58. function createRemoteConnection(desc) {
  59. const remoteDesc = {
  60. type: "answer",
  61. sdp: desc
  62. }
  63. localConnection.setRemoteDescription(remoteDesc).then((e) => {
  64. console.log(e)
  65. });
  66. }
  67. const sendButton = document.getElementById('sendDataBtn')
  68. sendButton.addEventListener('click', sendMessage, false)
  69. function sendMessage() {
  70. const messageText = document.getElementById('sendData').value;
  71. sendChannel.send(messageText);
  72. }
  73. sendChannel.onmessage = (msg) => {
  74. document.body.append(msg.data);
  75. }
  76. }