Skip to content

Instantly share code, notes, and snippets.

@bma73
Created June 13, 2015 19:29
Show Gist options
  • Select an option

  • Save bma73/110205f1f7fc1fa3a0d1 to your computer and use it in GitHub Desktop.

Select an option

Save bma73/110205f1f7fc1fa3a0d1 to your computer and use it in GitHub Desktop.
Unity3D: Load JSON data compressed with "deflate" from a NodeJS server...
using UnityEngine;
using System.Collections;
using SimpleJSON;
using System.IO;
/*
* Uses SimpleJSON
* http://wiki.unity3d.com/index.php/SimpleJSON
* and
* SharpZipLib
* http://icsharpcode.github.io/SharpZipLib/
*
*/
public class Data : MonoBehaviour {
void Start () {
StartCoroutine(LoadData());
}
IEnumerator LoadData() {
string url = "localhost:8080/data";
WWW www = new WWW (url);
yield return www;
byte[] uncompressed;
using(var stream = new MemoryStream(www.bytes))
{
using (var zip = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(stream))
{
var mo = new MemoryStream();
byte[] buffer = new byte[16 * 1024];
int read;
while ((read = zip.Read(buffer, 0, buffer.Length)) > 0)
{
mo.Write (buffer, 0, read);
}
uncompressed = mo.ToArray();
string src = System.Text.Encoding.UTF8.GetString(uncompressed);
JSONNode data = JSONNode.Parse (src);
Debug.Log(string.Format("id:{0}, info:{1}", data["id"], data["info"]));
}
}
}
}
var http = require('http');
var url = require('url');
var zlib = require('zlib');
var bigJSONData = {'id':1, info:"Big JSON Data!", data:[ 1, 2, 3, 4] };
http.createServer(function (req, res) {
var path = url.parse(req.url, true).pathname;
if (path == '/data') {
zlib.deflate(JSON.stringify(bigJSONData), function (err, buffer) {
if (err) {
res.writeHead(500);
res.end();
return;
}
res.writeHead(200, {'Content-Type': 'application/message'});
res.write(buffer, 'binary');
res.end();
});
} else {
res.writeHead(404);
res.end();
}
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment