I’m working on a Unity 3D game at the moment that needs a global leaderboard system that works across platform and not tied into the likes of Google Play or Game Centre. After taking a look at various technologies including my old favourite .NET (specifically thew newish .NET Core) I decided to use node.js because a) I want to learn it and b) .NET is a bit of overkill I think.
So I installed node.js then wrote a small server:
[sourcecode language=”js”]
"use strict";
var http = require("http");
class Server
{
constructor()
{
this.port = 8080;
this.ip = "localhost";
this.start();
}
start()
{
this.server = http.createServer((req, res) =>
{
this.processRequest(req, res);
});
this.server.on("clientError", (err, socket) =>
{
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
});
console.log("Server created");
}
listen()
{
this.server.listen(this.port, this.ip);
console.log("Server listening for connections");
}
processRequest(req, res)
{
// Process the request from the client
// We are only supporting POST
if (req.method === "POST")
{
// Post data may be sent in chunks so need to build it up
var body = "";
req.on("data", (data) =>
{
body += data;
// Prevent large files from benig posted
if (body.length > 1024)
{
// Tell Unity that the data sent was too large
res.writeHead(413, "Payload Too Large", {"Content-Type": "text/html"});
res.end("Error 413");
}
});
req.on("end", () =>
{
// Now that we have all data from the client, we process it
console.log("Received data: " + body);
// Split the key / pair values and print them out
var vars = body.split("&");
for (var t = 0; t < vars.length; t++)
{
var pair = vars[t].split("=");
var key = decodeURIComponent(pair[0]);
var val = decodeURIComponent(pair[1]);
console.log(key + ":" + val);
}
// Tell Unity that we received the data OK
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("OK");
});
}
else
{
// Tell Unity that the HTTP method was not allowed
res.writeHead(405, "Method Not Allowed", {"Content-Type": "text/html"});
res.end("Error 405");
}
}
}
module.exports.Server = Server;
[/sourcecode]
Create a file called server.js and add the above code.
Note that the above code is designed as a module so you can import it into your own code, e.g.:
[sourcecode language=”js”]
var server = require(‘./server’);
var httpServer = new server.Server();
httpServer.listen();
[/sourcecode]
Create a file called main.js and add the above code. Run the server by running node main.js
In the server code we create an instance of a HTTP client then we begin listening for connections. When a connection comes in we read the POST data and print out the key / value pairs that are sent.
On the Unity side we write the following code to test out our mini server:
[sourcecode language=”csharp”]
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class Leaderboards : MonoBehaviour
{
private static string _Url = "http://localhost";
private static string _Port = "8080";
public void SubmitScore(int which, int score)
{
StartCoroutine(SubmitScoreToServer(which, score));
}
private IEnumerator SubmitScoreToServer(int which, int score)
{
Debug.Log("Submitting score");
// Create a form that will contain our data
WWWForm form = new WWWForm();
form.AddField("which", which.ToString());
form.AddField("score", score.ToString());
// Create a POST web request with our form data
UnityWebRequest www = UnityWebRequest.Post(_Url + ":" + _Port, form);
// Send the request and yield until the send completes
yield return www.Send();
if (www.isError)
{
// There was an error
Debug.Log(www.error);
}
else
{
if (www.responseCode == 200)
{
// Response code 200 signifies that the server had no issues with the data we went
Debug.Log("Form sent complete!");
Debug.Log("Response:" + www.downloadHandler.text);
}
else
{
// Any other response signifies that there was an issue with the data we sent
Debug.Log("Error response code:" + www.responseCode.ToString());
}
}
}
}
[/sourcecode]
In the above code we create a form, add the data that we wish to send then create a web request (UnityWebRequest) to send the form to our test server. We send the request then yield the coroutine until the send completes. We finally test the response code to ensure that our data was sent ok,
To test, add the component to an object and then call SubmitScore(1, 100), you should see the following displayed from node:
Server created
Server listening for connections
Received data: which=1&score=100
which:1
score:100
And in the Unity console you should see:
Submitting score
Form sent complete!
Response:OK
At the moment this is still pretty much test code and doesn’t handle security other than to check for idiots sending really POST data. You should really encrypt the data sent to the server to prevent even bigger idiots from spamming your server with false information.
Next I will be looking at redis as a persistent store for my leaderboard data. I will be extending the node.js server code to include this functionality. I may do a blog on redis soon and then one another that includes details on how to use redis to create a leaderboard.