answerScript.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. (function (){
  2. const urlParams = new URLSearchParams(window.location.search);
  3. const connectionParam = urlParams.get('connection')
  4. const connection = JSON.parse(atob(connectionParam));
  5. console.dir(connection);
  6. createRemoteConnection(connection);
  7. })();
  8. function createRemoteConnection(remoteDescJSON) {
  9. const remoteDesc = {
  10. type: "offer",
  11. sdp: remoteDescJSON.description
  12. }
  13. const remoteCandidate = {
  14. candidate: remoteDescJSON.candidate,
  15. sdpMid: "0", // Media stream ID for audio
  16. sdpMLineIndex: 0 // Something to do with media
  17. }
  18. const remoteConnection = new RTCPeerConnection();
  19. const connectionInfo = {};
  20. remoteConnection.setRemoteDescription(remoteDesc).then((e) => {
  21. console.log(e)
  22. });
  23. remoteConnection.addIceCandidate(remoteCandidate).then(
  24. () => {console.log('yes')}
  25. )
  26. remoteConnection.createAnswer().then((desc) => {
  27. remoteConnection.setLocalDescription(desc);
  28. console.dir(desc);
  29. connectionInfo.description = desc.sdp;
  30. })
  31. remoteConnection.onicecandidate = e => {
  32. if (e.candidate) {
  33. const candidate = e.candidate.candidate;
  34. connectionInfo.candidate = candidate;
  35. const body = JSON.stringify(connectionInfo)
  36. fetch(
  37. 'http://localhost:8000/state/json',
  38. {
  39. method: 'post',
  40. headers: {'Content-Type': 'application/json'},
  41. body
  42. }
  43. ).then(response => {
  44. if (response.status !== 200) {
  45. throw new Error('bad status ' + response.status);
  46. }
  47. })
  48. }
  49. }
  50. remoteConnection.onicecandidateerror = err => {
  51. console.log(err)
  52. }
  53. remoteConnection.ondatachannel = (e) => {
  54. console.log('onDataChannel')
  55. const receiveChannel = e.channel;
  56. console.dir(receiveChannel);
  57. receiveChannel.onmessage = (msg) => {
  58. document.body.append(msg.data);
  59. }
  60. }
  61. }