用Netty和Raphael來寫塔防online遊戲(二) - JS中使用protobuf協議

一. 簡單介紹一下protobuf:html

Protocol Buffers are a language-neutral, platform-neutral, extensible way of serializing structured data for use in communications protocols, data storage, and more, originally designed at Google .git

現在,已經有人用JS實現了protobuf協議,就是ProtoBuf.js,因而可知谷哥的號召力非同通常啊。github

ProtoBuf.js同時支持NodeJS和Browser,也就是說,如今咱們能夠在JS client端使用protobuf!固然,前提是咱們使用的是高級瀏覽器,由於ProtoBuf.js依賴於ByteBuffer.js(一個對ArrayBuffer進行了封裝的類庫),因此,只能say byebye to IE < 10。json

二. 爲何要使用protobuf瀏覽器

舉個很簡單的例子:socket

client向server發送這樣一個消息,ui

使用json格式:code

{
    "model": "Rusty",
    "vendor": {
        "name": "occume",
        "address": {
            "country": "china"
        }
    },
    "speed": "SUPERFAST"
}
服務端會收到95個字節,
一樣的消息,使用protobuf格式:

[10 5 82 117 115 116 121 18 17 10 9 73 114 111 110 32 73 110 99 46 18 4 10 2 85 83 24 2]orm

服務端收到28個字節server

兩者的區別顯而易見,尤爲是在移動端等須要節省流量的地方,protobuf的優點就更不用說了。

三. protobuf的簡單用法

依賴如下JS

Long.min.js 可選
ByteBufferAB.min.js

ProtoBuf.min.js

而後須要定義一個proto文件,以官網的爲例(complex.proto)。

關鍵代碼:

encode:

var	ProtoBuf = dcodeIO.ProtoBuf,
	Message = ProtoBuf.loadProtoFile("./example.proto").build("Message"),
	Game = ProtoBuf.loadProtoFile("./complex.proto").build("Game"),
	Car = Game.Cars.Car;

var car = new Car({
    "model": "Rusty",
    "vendor": {
        "name": "Iron Inc.",
        "address": {
            "country": "US"
        }
    },
    "speed": "SUPERFAST" // also equivalent to "speed": 2
});

socket.send(car.toArrayBuffer());
decode:
var car = Car.decode(evt.data);
console.log(car.model);

以上是對一個簡單的類的encode和decode,在具體的應用中,只須要根據不一樣的業務須要,編寫相對應的proto文件就Ok了。

項目地址:https://github.com/occume/D3000

相關文章
相關標籤/搜索