Search code examples
javascripthtmlvariablesjsfiddlechannel

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


I am working on a project to make a three.js multiplayer game. I finished the basics and all I need to do now is to add the multiplayer part. I figured out that there was this thing called RTC I could use without making a server complicatedly. All I need to do is send a player position's variables through the channel so a random player can see another player's character. I am kind of struggling, so is there anyone out there that can help me complete this separate code? Thank you! Also I am using 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>


Solution

  • While I am by no means a WebRTC expert, I know it can send strings (see MDN). I think the best way to accomplish your goal is to convert the variables to an object, and convert the object to a string that can be sent. Then, on the other end, you can decode the string and get the data. Here's a demonstration (without 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);