-
Notifications
You must be signed in to change notification settings - Fork 2
/
package.ts
77 lines (73 loc) · 2.51 KB
/
package.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Learn TypeScript:
// - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
import Protocol from "./protocol";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Package {
static TYPE_HANDSHAKE = 1;
static TYPE_HANDSHAKE_ACK = 2;
static TYPE_HEARTBEAT = 3;
static TYPE_DATA = 4;
static TYPE_KICK = 5;
/**
* Package protocol encode.
*
* Pomelo package format:
* +------+-------------+------------------+
* | type | body length | body |
* +------+-------------+------------------+
*
* Head: 4bytes
* 0: package type,
* 1 - handshake,
* 2 - handshake ack,
* 3 - heartbeat,
* 4 - data
* 5 - kick
* 1 - 3: big-endian body length
* Body: body length bytes
*
* @param {Number} type package type
* @param {ByteArray} body body content in bytes
* @return {ByteArray} new byte array that contains encode result
*/
static encode(type, body?) {
var length = body ? body.length : 0;
var buffer = new Uint8Array(Protocol.PKG_HEAD_BYTES + length);
var index = 0;
buffer[index++] = type & 0xff;
buffer[index++] = (length >> 16) & 0xff;
buffer[index++] = (length >> 8) & 0xff;
buffer[index++] = length & 0xff;
if (body) {
Protocol.copyArray(buffer, index, body, 0, length);
}
return buffer;
};
/**
* Package protocol decode.
* See encode for package format.
*
* @param {ByteArray} buffer byte array containing package content
* @return {Object} {type: package type, buffer: body byte array}
*/
static decode(buffer) {
var offset = 0;
var bytes = new Uint8Array(buffer);
var length = 0;
var rs = [];
while (offset < bytes.length) {
var type = bytes[offset++];
length = ((bytes[offset++]) << 16 | (bytes[offset++]) << 8 | bytes[offset++]) >>> 0;
var body = length ? new Uint8Array(length) : null;
Protocol.copyArray(body, 0, bytes, offset, length);
offset += length;
rs.push({ 'type': type, 'body': body });
}
return rs.length === 1 ? rs[0] : rs;
};
}