-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
packet.ts
84 lines (75 loc) · 2.08 KB
/
packet.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
78
79
80
81
82
83
84
import { byteFormat } from "../../deps.ts";
import { BufferReader, BufferWriter } from "../buffer.ts";
import { WriteError } from "../consttants/errors.ts";
import { debug, log } from "../logger.ts";
/** @ignore */
interface PacketHeader {
size: number;
no: number;
}
/** @ignore */
export class SendPacket {
header: PacketHeader;
constructor(readonly body: Uint8Array, no: number) {
this.header = { size: body.length, no };
}
async send(conn: Deno.Conn) {
const body = this.body as Uint8Array;
const data = new BufferWriter(new Uint8Array(4 + body.length));
data.writeUints(3, this.header.size);
data.write(this.header.no);
data.writeBuffer(body);
log.debug(`send: ${data.length}B \n${byteFormat(data.buffer)}\n`);
try {
await conn.write(data.buffer);
} catch (error) {
throw new WriteError(error.message);
}
}
}
/** @ignore */
export class ReceivePacket {
header: PacketHeader;
body: BufferReader;
type: "EOF" | "OK" | "ERR" | "RESULT";
async parse(reader: Deno.Reader): Promise<ReceivePacket> {
const header = new BufferReader(new Uint8Array(4));
let readCount = 0;
let nread = await reader.read(header.buffer);
if (nread === Deno.EOF) return null;
readCount = nread;
this.header = {
size: header.readUints(3),
no: header.readUint8()
};
this.body = new BufferReader(new Uint8Array(this.header.size));
nread = await reader.read(this.body.buffer);
if (nread === Deno.EOF) return;
readCount += nread;
switch (this.body.buffer[0]) {
case 0x00:
this.type = "OK";
break;
case 0xff:
this.type = "ERR";
break;
case 0xfe:
this.type = "EOF";
break;
default:
this.type = "RESULT";
break;
}
debug(() => {
const data = new Uint8Array(readCount);
data.set(header.buffer);
data.set(this.body.buffer, 4);
log.debug(
`receive: ${readCount}B, size = ${this.header.size}, no = ${
this.header.no
} \n${byteFormat(data)}\n`
);
});
return this;
}
}