用Netty和Raphael来写塔防online游戏(二)

一. 简单介绍一下protobuf:

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 .

如今,已经有人用JS实现了protobuf协议,就是ProtoBuf.js,由此可见谷哥的号召力非同一般啊。

ProtoBuf.js同时支持NodeJS和Browser,也就是说,现在我们可以在JS client端使用protobuf!当然,前提是我们使用的是高级浏览器,因为ProtoBuf.js依赖于ByteBuffer.js(一个对ArrayBuffer进行了封装的类库),所以,只能say byebye to IE < 10。

二. 为什么要使用protobuf

举个很简单的例子:

client向server发送这样一个消息,

使用json格式:

{
    "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]

服务端收到28个字节

二者的区别显而易见,尤其是在移动端等需要节省流量的地方,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

原文地址:https://www.cnblogs.com/occume/p/3899601.html