-
Notifications
You must be signed in to change notification settings - Fork 0
/
panrpc-example-websocket-client-cli.ts
239 lines (192 loc) · 5.62 KB
/
panrpc-example-websocket-client-cli.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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* eslint-disable no-console */
import { env, exit, stdin, stdout } from "process";
import { createInterface } from "readline/promises";
import { parse } from "url";
// eslint-disable-next-line import/no-extraneous-dependencies
import { JSONParser } from "@streamparser/json-whatwg";
// eslint-disable-next-line import/no-extraneous-dependencies
import { WebSocket, WebSocketServer } from "ws";
import { ILocalContext, IRemoteContext, Registry } from "../index";
class Local {
// eslint-disable-next-line class-methods-use-this
async Println(ctx: ILocalContext, msg: string) {
console.log("Printing message", msg, "for remote with ID", ctx.remoteID);
console.log(msg);
}
}
class Remote {
// eslint-disable-next-line class-methods-use-this, @typescript-eslint/no-unused-vars
async Increment(ctx: IRemoteContext, delta: number): Promise<number> {
return 0;
}
}
let clients = 0;
const registry = new Registry(
new Local(),
new Remote(),
{
onClientConnect: () => {
clients++;
console.log(clients, "clients connected");
},
onClientDisconnect: () => {
clients--;
console.log(clients, "clients connected");
},
}
);
(async () => {
console.log(`Enter one of the following letters followed by <ENTER> to run a function on the remote(s):
- a: Increment remote counter by one
- b: Decrement remote counter by one`);
const rl = createInterface({ input: stdin, output: stdout });
// eslint-disable-next-line no-constant-condition
while (true) {
const line =
// eslint-disable-next-line no-await-in-loop
await rl.question("");
// eslint-disable-next-line no-await-in-loop
await registry.forRemotes(async (remoteID, remote) => {
console.log("Calling functions for remote with ID", remoteID);
switch (line) {
case "a":
try {
// eslint-disable-next-line no-await-in-loop
const res = await remote.Increment(undefined, 1);
console.log(res);
} catch (e) {
console.error(`Got error for Increment func: ${e}`);
}
break;
case "b":
try {
// eslint-disable-next-line no-await-in-loop
const res = await remote.Increment(undefined, -1);
console.log(res);
} catch (e) {
console.error(`Got error for Increment func: ${e}`);
}
break;
default:
console.log(`Unknown letter ${line}, ignoring input`);
}
});
}
})();
const addr = env.ADDR || "127.0.0.1:1337";
const listen = env.LISTEN === "true";
if (listen) {
const u = parse(`ws://${addr}`);
const server = new WebSocketServer({
host: u.hostname as string,
port: parseInt(u.port as string, 10),
});
server.on("connection", (socket) => {
socket.addEventListener("error", (e) => {
console.error("Client disconnected with error:", e);
});
const linkSignal = new AbortController();
const encoder = new WritableStream({
write(chunk) {
socket.send(JSON.stringify(chunk));
},
});
const parser = new JSONParser({
paths: ["$"],
separator: "",
});
const parserWriter = parser.writable.getWriter();
const parserReader = parser.readable.getReader();
const decoder = new ReadableStream({
start(controller) {
parserReader
.read()
.then(async function process({ done, value }) {
if (done) {
controller.close();
return;
}
controller.enqueue(value?.value);
parserReader
.read()
.then(process)
.catch((e) => controller.error(e));
})
.catch((e) => controller.error(e));
},
});
socket.addEventListener("message", (m) =>
parserWriter.write(m.data as string)
);
socket.addEventListener("close", () => {
parserReader.cancel();
parserWriter.abort();
linkSignal.abort();
});
registry.linkStream(
linkSignal.signal,
encoder,
decoder,
(v) => v,
(v) => v
);
});
console.log("Listening on", addr);
} else {
const socket = new WebSocket(`ws://${addr}`);
socket.addEventListener("error", (e) => {
console.error("Disconnected with error:", e);
exit(1);
});
socket.addEventListener("close", () => exit(0));
await new Promise<void>((res, rej) => {
socket.addEventListener("open", () => res());
socket.addEventListener("error", rej);
});
const linkSignal = new AbortController();
const encoder = new WritableStream({
write(chunk) {
socket.send(JSON.stringify(chunk));
},
});
const parser = new JSONParser({
paths: ["$"],
separator: "",
});
const parserWriter = parser.writable.getWriter();
const parserReader = parser.readable.getReader();
const decoder = new ReadableStream({
start(controller) {
parserReader
.read()
.then(async function process({ done, value }) {
if (done) {
controller.close();
return;
}
controller.enqueue(value?.value);
parserReader
.read()
.then(process)
.catch((e) => controller.error(e));
})
.catch((e) => controller.error(e));
},
});
socket.addEventListener("message", (m) =>
parserWriter.write(m.data as string)
);
socket.addEventListener("close", () => {
parserReader.cancel();
parserWriter.abort();
linkSignal.abort();
});
registry.linkStream(
linkSignal.signal,
encoder,
decoder,
(v) => v,
(v) => v
);
console.log("Connected to", addr);
}