-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprotocol.mjs
More file actions
115 lines (93 loc) · 2.38 KB
/
Copy pathprotocol.mjs
File metadata and controls
115 lines (93 loc) · 2.38 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import { Buffer } from "node:buffer";
import createDebug from "debug";
const debug = createDebug("protocol");
const SIZE_BYTES_COUNT = 4;
const HEADER_BYTES_COUNT = 3;
const COMMAND_OFFSET = SIZE_BYTES_COUNT + HEADER_BYTES_COUNT;
const COMMAND_CODES = {
LOGIN: 0x01,
MESSAGE: 0x02,
};
const RESPONSE_CODES = {
OK: 0x01,
// ???: =0x02,
USER_NOT_FOUND: 0x03,
USER_ALREADY_LOGGED: 0x04,
};
const readMessangeLength = (buffer) => {
return buffer.readUInt32BE();
};
const readHeader = (buffer) => {
const version = buffer.readUInt8(SIZE_BYTES_COUNT);
const command = buffer.readUInt16BE(SIZE_BYTES_COUNT + 1);
return {
version,
command,
};
};
const readCommandLoginBody = (buffer) => {
const correlationId = buffer.readUInt32BE(COMMAND_OFFSET);
const stringLength = buffer.readUInt16BE(COMMAND_OFFSET + 4);
const username = buffer.toString(
"utf8",
COMMAND_OFFSET + 6,
COMMAND_OFFSET + 6 + stringLength
);
return {
correlationId,
username,
};
};
const readCommandMessageBody = (buffer) => {
let offset = COMMAND_OFFSET;
const correlationId = buffer.readUInt32BE(offset);
offset += 4;
let stringLength = buffer.readUInt16BE(offset);
offset += 2;
const message = buffer.toString("utf8", offset, offset + stringLength);
offset += stringLength;
stringLength = buffer.readUInt16BE(offset);
offset += 2;
const from = buffer.toString("utf8", offset, offset + stringLength);
offset += stringLength;
stringLength = buffer.readUInt16BE(offset);
offset += 2;
const to = buffer.toString("utf8", offset, offset + stringLength);
offset += stringLength;
const time = buffer.readBigUInt64BE(offset);
offset += 8;
return {
correlationId,
message,
from,
to,
time,
};
};
const createResponse = (correlationId, code) => {
const buffer = Buffer.alloc(13);
let offset = 0;
buffer.writeUInt32BE(0x09, offset);
offset += 4;
// write version
buffer.writeUInt8(0x01, offset);
offset += 1;
// write the command id: 0x03 == reponse
buffer.writeUInt16BE(0x03, offset);
offset += 2;
// send back the correlation id
buffer.writeUInt32BE(correlationId, offset);
offset += 4;
// response code
buffer.writeUInt16BE(code, offset);
return buffer;
};
export {
RESPONSE_CODES,
COMMAND_CODES,
readMessangeLength,
readHeader,
readCommandLoginBody,
readCommandMessageBody,
createResponse,
};