JavaScript Real-Time Guide

This is a guide for getting your JavaScript project set up for GameSparks' real-time services.

Read First! Please ensure you have followed our general guide on real-time services before you attempt to apply it for Javascript and to learn how our real-time service works and what you should expect from it.

Adding the gamesparks-rt File into your Project

Download the JavaScript SDK and copy the gamesparks-rt.js file to your project.

Important! The Real-Time SDK is dependent on the base JavaScript SDK. You must ensure that you follow the set up steps for the base SDK before implementing Real-Time features.

RT Setup

We've placed the following logic in our gamesparks.html in the sample project. You can place it in any HTML file that's running your real-time logic.

1. Include the gamesparks-rt file using the script tag:

<script type="text/javascript" src="gamesparks-rt.js"></script>

2. Create the real-time session class:

var myRTSession = function() {};

3. Add the following variables to your session class:

myRTSession.started = false;
myRTSession.onPlayerConnectCB = null;
myRTSession.onPlayerDisconnectCB = null;
myRTSession.onReadyCB = null;
myRTSession.onPacketCB = null;
myRTSession.session = null;

4. Add and assign the following functions to the RT session:

myRTSession.start = function(connectToken, host, port) {
  var index = host.indexOf(":");
  var theHost;

  if (index > 0) {
    theHost = host.slice(0, index);
  } else {
    theHost = host;
  }

  console.log(theHost + " : " + port);

  myRTSession.session = GameSparksRT.getSession(connectToken, theHost, port, myRTSession);
  if (myRTSession.session != null) {
    myRTSession.started = true;

    myRTSession.session.start();
  } else {
    myRTSession.started = false;
  }
};
myRTSession.stop = function() {
  myRTSession.started = false;

    if (myRTSession.session != null) {
      myRTSession.session.stop();
    }
};

myRTSession.log = function(message) {
  var peers = "|";

  for (var k in myRTSession.session.activePeers) {
    peers = peers + myRTSession.session.activePeers[k] + "|";
  }

  console.log(myRTSession.session.peerId + ": " + message + " peers:" + peers);
};
myRTSession.onPlayerConnect = function(peerId) {
  myRTSession.log(" OnPlayerConnect:" + peerId);

  if (myRTSession.onPlayerConnectCB != null) {
    myRTSession.onPlayerConnectCB(peerId);
  }
};

myRTSession.onPlayerDisconnect = function(peerId) {
  myRTSession.log(" OnPlayerDisconnect:" + peerId);

  if (myRTSession.onPlayerDisconnectCB != null) {
    myRTSession.onPlayerDisconnectCB(peerId);
  }
};

myRTSession.onReady = function(ready) {
  myRTSession.log(" OnReady:" + ready.toString());

  if (myRTSession.onReadyCB != null) {
    myRTSession.onReadyCB(ready);
  }
};

myRTSession.onPacket = function(packet) {
  myRTSession.log(" OnPacket:" + packet.toString());

  if (myRTSession.onPacketCB != null) {
    myRTSession.onPacketCB(packet);
  }
};

5. Create a function to send a MatchmakingRequest:

function sendMatchmakingRequest() {
  //Create a matchmaking request an add the values for your game's match
  gamesparks.sendWithData("MatchmakingRequest",
      {
            skill: 1,
            matchShortCode: "Match_STD"
        },
        function(response) {
          if (response.error) {
        console.error(JSON.stringify(response.error));
      } else {
        console.log("Match OK...");
      }
        }
    );
}

6. Add a listener for both the MatchFoundMessage and the MatchNotFound messages. This will be in your message handler function assigned in your GS init function:

function onMessageRT(message) {
  //console.log("message " + JSON.stringify(message));
  if (message["@class"] === ".MatchFoundMessage") {
    var accessToken = message["accessToken"];
    var host = message["host"];
    var port = message["port"];

    myRTSession.stop();

    if (myTimer) {
      clearTimeout(myTimer);
    }

    myTimer = setInterval(mainRTLoop, 10);

    myRTSession.start(accessToken, host, port);
  } else if (message["@class"] === ".MatchNotFoundMessage") {
    console.log("MATCH NOT FOUND");

    sendMatchmakingRequest();
  }
}

7. In your update function add:

if (myRTSession.started) {
  //If the session exists
  if(myRTSession.session != null){
    //Update the session
    myRTSession.session.update();
  }
}

Sending Packets

To send packets:

1. Create an RTData object:

var data = RTData.get();

2. If you wish to send data with your packet, then populate your RTData object with variables - starting first with the index of the variable and then the value:

//Set Number
data.setLong(int, varLong)
//Set Vector
data.setRTVector(int, varVector)
//Set Float
data.setFloat(int, varFloat)
//Set Double
data.setDouble(int, varDouble)
//Set String
data.setString(int, varString)
//Set nested data object
data.setData(int, varData)

3. Send the Data in a packet through the session's send function. Give the packet an OPCode, the RTData object, the intent, and the recipients (If the recipients are not specified, the packet will be sent to all active players) and send it:

  myRTSession.session.sendRTData(1, GameSparksRT.deliveryIntent.RELIABLE, data, []);

Receiving Packets

Edit the Packet callback function to suit the packets you're receiving by comparing the OpCode of the packet and processing it appropriately:

myRTSession.onPacket = function(packet) {
  // Choose what to do with a packet depending on its opCode
  if (packet.opCode == 1) {
    // Use packet.data to access the data in your packet and reference the type and index position of the variable
    console.log("DATA IS " + packet.data.getLong(1));
  }
};
Did this page help you? Please enter your feedback below. For questions about using this part of the platform, please contact support here