2019-05-14 15:19:12 -04:00
|
|
|
import {
|
|
|
|
connectWebSocket,
|
|
|
|
isWebSocketCloseEvent,
|
|
|
|
isWebSocketPingEvent,
|
|
|
|
isWebSocketPongEvent
|
|
|
|
} from "../ws/mod.ts";
|
2019-05-26 19:58:31 -04:00
|
|
|
import { encode } from "../strings/mod.ts";
|
2019-05-14 15:19:12 -04:00
|
|
|
import { BufReader } from "../io/bufio.ts";
|
|
|
|
import { TextProtoReader } from "../textproto/mod.ts";
|
2019-08-24 13:38:18 -04:00
|
|
|
import { blue, green, red, yellow } from "../fmt/colors.ts";
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2020-02-20 10:19:14 -05:00
|
|
|
const endpoint = Deno.args[0] || "ws://127.0.0.1:8080";
|
2019-05-14 15:19:12 -04:00
|
|
|
/** simple websocket cli */
|
2019-10-27 09:04:42 -04:00
|
|
|
const sock = await connectWebSocket(endpoint);
|
|
|
|
console.log(green("ws connected! (type 'close' to quit)"));
|
|
|
|
(async function(): Promise<void> {
|
|
|
|
for await (const msg of sock.receive()) {
|
|
|
|
if (typeof msg === "string") {
|
|
|
|
console.log(yellow("< " + msg));
|
|
|
|
} else if (isWebSocketPingEvent(msg)) {
|
|
|
|
console.log(blue("< ping"));
|
|
|
|
} else if (isWebSocketPongEvent(msg)) {
|
|
|
|
console.log(blue("< pong"));
|
|
|
|
} else if (isWebSocketCloseEvent(msg)) {
|
|
|
|
console.log(red(`closed: code=${msg.code}, reason=${msg.reason}`));
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
|
|
|
}
|
2019-10-27 09:04:42 -04:00
|
|
|
})();
|
2019-05-14 15:19:12 -04:00
|
|
|
|
2019-10-27 09:04:42 -04:00
|
|
|
const tpr = new TextProtoReader(new BufReader(Deno.stdin));
|
|
|
|
while (true) {
|
|
|
|
await Deno.stdout.write(encode("> "));
|
2020-02-17 12:49:30 -05:00
|
|
|
const line = await tpr.readLine();
|
|
|
|
if (line === Deno.EOF) {
|
2019-10-27 09:04:42 -04:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
if (line === "close") {
|
|
|
|
break;
|
|
|
|
} else if (line === "ping") {
|
|
|
|
await sock.ping();
|
|
|
|
} else {
|
|
|
|
await sock.send(line);
|
|
|
|
}
|
|
|
|
// FIXME: Without this,
|
|
|
|
// sock.receive() won't resolved though it is readable...
|
2019-11-13 13:42:34 -05:00
|
|
|
await new Promise((resolve): void => {
|
|
|
|
setTimeout(resolve, 0);
|
|
|
|
});
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|
2019-10-27 09:04:42 -04:00
|
|
|
await sock.close(1000);
|
|
|
|
// FIXME: conn.close() won't shutdown process...
|
|
|
|
Deno.exit(0);
|