-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathwsc
executable file
·112 lines (94 loc) · 2.32 KB
/
wsc
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
#!/usr/bin/env node
const WebSocket = require('ws');
const parser = require('meow');
const chalk = require('chalk');
const readline = require('readline');
const cli = parser(`
Usage
$ wsc [options] ws://echo.websocket.org
Options
-e, --eval Evaluate input as JS and encode as JSON
-r, --roundtrip Track roundtrip time between sent/recv
-t, --time Print a timestamp in ms before each line
-p, --protocol <str> Set protocol
-M Disable masking
-C Disable color output
`, {
boolean: ['e', 'r', 't', 'M', 'C'],
string: ['p'],
alias: {
e: 'eval',
r: 'roundtrip',
t: 'time',
p: 'protocol'
}
});
if (!cli.input.length) {
console.error('Missing url');
process.exit(1);
}
chalk.enabled = !cli.flags.C;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
}).on('SIGINT', () => {
console.log();
process.exit();
});
const url = cli.input[0];
const ws = new WebSocket(url, cli.flags.protocol);
ws.on('open', () => {
var sent = Date.now();
console.log(chalk.green(`Connected to ${url}`));
rl.prompt();
ws.on('error', (err) => {
console.error(`Connection error: ${err}`);
process.exit(1);
}).on('close', () => {
console.log('Connection closed');
process.exit(0);
}).on('message', (message, flags) => {
var output = '';
var recv = Date.now();
if (cli.flags.time) {
output += `${recv} `;
}
if (flags.binary) {
output += '< Binary data received';
} else {
output += `< ${message}`;
}
if (cli.flags.roundtrip) {
output += ` (${recv - sent}ms)`;
}
clear();
console.log(chalk.gray(output));
rl.prompt();
});
rl.on('line', (input) => {
const message = cli.flags.eval ? tryEval(input) : input;
sent = Date.now();
if (cli.flags.time) {
clearPrev();
console.log(`${sent} > ${input}`);
rl.prompt();
}
ws.send(message, {mask: !cli.flags.M});
rl.prompt();
});
});
function clear() {
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
}
function clearPrev() {
readline.moveCursor(process.stdout, 0, -1);
clear();
}
function tryEval(str) {
try {
return JSON.stringify(eval(`(${str})`));
} catch (e) {
return str;
}
}