有没有办法在 JS 中通过 RTC 发送变量?

Is there a way to send variables through RTC in JS?

我正在做一个 three.js 多人游戏的项目。我完成了基础知识,现在我需要做的就是添加多人游戏部分。我发现有一个叫做 RTC 的东西我可以使用而无需复杂地制作服务器。我需要做的就是通过通道发送玩家位置的变量,以便随机玩家可以看到另一个玩家的角色。我有点挣扎,所以有没有人可以帮助我完成这个单独的代码?谢谢!我也在使用 JSFiddle。 https://jsfiddle.net/Plain_Gamer/cqvh78dr/22/

function startup() {
  connectButton = document.getElementById('connectButton');
  disconnectButton = document.getElementById('disconnectButton');
  sendButton = document.getElementById('sendButton');
  messageInputBox = document.getElementById('message');
  receiveBox = document.getElementById('receivebox');

  connectButton.addEventListener('click', connectPeers, false);
  disconnectButton.addEventListener('click', disconnectPeers, false);
  sendButton.addEventListener('click', sendMessage, false);
}

localConnection = new RTCPeerConnection();

sendChannel = localConnection.createDataChannel(prompt('Create channel name...'));
remoteConnection = new RTCPeerConnection(prompt('Enter channel name...'));
remoteConnection.ondatachannel = RTCRtpReceiver;
<button id="connectButton" name="connectButton" class="buttonleft">
  Connect
</button>
<button id="disconnectButton" name="disconnectButton" class="buttonright" disabled>
  Disconnect
</button>
<div class="messagebox">
  <label for="message">Enter a message:
    <input type="text" name="message" id="message" placeholder="Message text" inputmode="latin" size=60 maxlength=120 disabled>
  </label>
  <button id="sendButton" name="sendButton" class="buttonright" disabled>
    Send
  </button>
</div>
<div class="messagebox" id="receivebox">
  <p>Messages received:</p>
</div>

虽然我绝不是 WebRTC 专家,但我知道它可以发送字符串(参见 MDN)。我认为实现目标的最佳方法是将变量转换为对象,并将对象转换为可以发送的字符串。然后,在另一端,您可以解码字符串并获取数据。这是一个演示(没有 WebRTC)。

let x = 0;
let y = 0;

// Convert variables x and y into an object
let obj = { x, y };

// Turn the object to a string
let str = JSON.stringify(obj);
console.log(str):

// Turn the string back into the object
let decodedObj = JSON.parse(str);
console.log(decodedObj);