javascript 使用手动信令的WebRTC双通道的完整示例

flvtvl50  于 6个月前  发布在  Java
关注(0)|答案(1)|浏览(60)

我真的很难得到一个完整的WebRTC双通道示例,我可以复制/粘贴,它的工作。
我想一个JavaScript的例子WebRTC的通道与手动信令,即,当例子加载,它提供了信令数据在一个文本框。
我手动复制数据(高亮显示,复制)并将其粘贴到对等体的窗口中,该窗口有一个文本框来接受该信令数据。我相信信令数据中需要有一个“答案”,因此也需要有相应的文本框等待该输入。
这个例子可以使用谷歌的免费STUN服务器吗?
我真的很困惑与位的例子.我想要一个文件,请,包含HTML和JavaScript(没有CSS或jQuery,请).这是足够的代码只工作在Chrome.

mbzjlibv

mbzjlibv1#

在这里。点击下面的蓝色按钮在two different tabs/windows/browsers/machines

const output = document.getElementById('output');
const config = {
  iceServers: [{
    urls: "stun:stun.l.google.com:19302" // list of free STUN servers: https://gist.github.com/zziuni/3741933
  }]
};
const pc = new RTCPeerConnection(config);
const dc = pc.createDataChannel("chat", {
  negotiated: true,
  id: 0
});
const log = msg => output.innerHTML += `<br>${msg}`;
dc.onopen = () => chat.select();
dc.onmessage = e => log(`> ${e.data}`);
pc.oniceconnectionstatechange = e => log(pc.iceConnectionState);

chat.onkeypress = function(e) {
  if (e.keyCode != 13) return;
  dc.send(chat.value);
  log(chat.value);
  chat.value = "";
};

async function createOffer() {
  button.disabled = true;
  await pc.setLocalDescription(await pc.createOffer());
  pc.onicecandidate = ({
    candidate
  }) => {
    if (candidate) return;
    offer.value = pc.localDescription.sdp;
    offer.select();
    answer.placeholder = "Paste answer here. And Press Enter";
  };
}

offer.onkeypress = async function(e) {
  if (e.keyCode != 13 || pc.signalingState != "stable") return;
  button.disabled = offer.disabled = true;
  await pc.setRemoteDescription({
    type: "offer",
    sdp: offer.value
  });
  await pc.setLocalDescription(await pc.createAnswer());
  pc.onicecandidate = ({
    candidate
  }) => {
    if (candidate) return;
    answer.focus();
    answer.value = pc.localDescription.sdp;
    answer.select();
  };
};

answer.onkeypress = function(e) {
  if (e.keyCode != 13 || pc.signalingState != "have-local-offer") return;
  answer.disabled = true;
  pc.setRemoteDescription({
    type: "answer",
    sdp: answer.value
  });
};

pc.onconnectionstatechange = ev => handleChange();
pc.oniceconnectionstatechange = ev => handleChange();

function handleChange() {
  let stat = 'ConnectionState: <strong>' + pc.connectionState + '</strong> IceConnectionState: <strong>' + pc.iceConnectionState + '</strong>';
  document.getElementById('stat').innerHTML = stat;
  console.log('%c' + new Date().toISOString() + ': ConnectionState: %c' + pc.connectionState + ' %cIceConnectionState: %c' + pc.iceConnectionState,
    'color:yellow', 'color:orange', 'color:yellow', 'color:orange');
}
handleChange();

个字符
然后按照以下步骤操作:
1.在窗口A中,按Offer按钮并将报价复制到剪贴板。
1.在窗口B中,将报价粘贴到“将报价粘贴到此处”,然后按Enter键。
1.复制几秒钟后出现的答案。
1.返回到窗口A并将答案粘贴到“将答案粘贴到此处”并按Enter。
您现在应该会看到一条消息,提示您已“连接”。在聊天框中键入内容即可聊天!
如果你和一个朋友以某种方式交换报价/答案,你现在就有了一个直接的点对点连接,这应该在世界各地都能工作(模对称NAT路由器);不涉及数据服务器。

相关问题