summaryrefslogtreecommitdiff
path: root/std/ws/example_client.ts
blob: a6649570ea5de72b8dc04d9f1614374ea577f30a (plain)
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
import {
  connectWebSocket,
  isWebSocketCloseEvent,
  isWebSocketPingEvent,
  isWebSocketPongEvent
} from "../ws/mod.ts";
import { encode } from "../strings/mod.ts";
import { BufReader } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts";
import { blue, green, red, yellow } from "../fmt/colors.ts";

const endpoint = Deno.args[1] || "ws://127.0.0.1:8080";
/** simple websocket cli */
async function main(): Promise<void> {
  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}`));
      }
    }
  })();
  const tpr = new TextProtoReader(new BufReader(Deno.stdin));
  while (true) {
    await Deno.stdout.write(encode("> "));
    const [line, err] = await tpr.readLine();
    if (err) {
      console.error(red(`failed to read line from stdin: ${err}`));
      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...
    await new Promise(
      (resolve): void => {
        setTimeout(resolve, 0);
      }
    );
  }
  await sock.close(1000);
  // FIXME: conn.close() won't shutdown process...
  Deno.exit(0);
}

if (import.meta.main) {
  main();
}