首页 > 代码库 > 参照protobuf,将json数据转换成二进制在网络中传输。

参照protobuf,将json数据转换成二进制在网络中传输。

json数据格式在网络中传输需要的数据比二进制庞大太多,我们可以省去key,外加将数字不需要编码成字符串,直接二进制编码就OK。


pack : 将json压包,unpack解包成json。

var Struct = module.exports = {};

Struct.TYPE = {
	int8:1,
	int16:2,
	int32:3,
	uint8:4,	
	uint16:5,
	uint32:7,
	string:8,
	object:9,
	aint8:10,
	aint16:11,
	aint32:12,
	auint8:13,
	auint16:14,
	auint32:15,
	aobject:16
};


//
Struct.unpack = function(proto, buf) {
	var _unpack = function(proto, buf, pos) {
		var p = {};
		var ret;
		var length;

		for (var k in proto) {
			var type = proto[k][0];
			if (typeof type == 'object') {
				var json = type;
				type = 'object';
			}
			if (proto[k].length == 2 && proto[k][1] == 'array') {
				type = 'a' + type;
			}
			var value = http://www.mamicode.com/[];>


测试代码:

var Struct = require('./struct');

var proto = {
    int8   : ['int8'],
    int16  : ['int16'],
    int32  : ['int32'],
    uint8  : ['uint8'],
    uint16 : ['uint16'],
    uint32 : ['uint32'],
    string : ['string'],
    aint8  : ['int8', 'array'],
    aint16 : ['int16', 'array'],
    aint32 : ['int32', 'array'],
    auint8 : ['uint8', 'array'],
    auint16: ['uint16', 'array'],
    auint32: ['uint32', 'array'],
    object : [
        {int8: ['int8'], int16: ['int16'], string: ['string'], astring: ['astring']}
    ],
    aobject : [
        {int8: ['int8'], int16: ['int16'], string: ['string'], astring: ['astring']},
        'array'
    ],
    astring: ['string', 'array']
}

var msg = {
    int8   : 12,
    int16  : 1234,
    int32  : 12345,
    uint8  : 130,// > 128
    uint16 : 32800, // >> 128 * 256
    uint32 : 3221245472, // >> 3 * (1<<30)
    string : 'hello world',
    aint8  : [-1, -2, -3, -5, -6],
    aint16 : [-11, -12, -13, -15, -17],
    aint32 : [-337, -338, -339, -3310, -3311],
    auint8 : [1, 2, 3, 4],
    auint16: [8, 9, 10, 11, 12],
    auint32: [12, 13, 15, 16],
    object : {int8: 12, int16: 1234, string: 'somebady', astring: ['save me', 'Dont stop me now']},
    aobject : [{int8: 12, int16: 1234, string: 'somebady', astring: ['save me', 'Dont stop me now']}, {int8: 12, int16: 1234, string: 'somebady', astring: ['save me', 'Dont stop me now']}],
    astring: ['melo', 'kaka', 'much', 'save']
}


var buf = Struct.pack(proto, msg);
console.log(buf);

var remsg = Struct.unpack(proto, buf);
console.log(JSON.stringify(remsg));