Created
June 13, 2015 19:29
-
-
Save bma73/110205f1f7fc1fa3a0d1 to your computer and use it in GitHub Desktop.
Unity3D: Load JSON data compressed with "deflate" from a NodeJS server...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"])); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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