mockserver.js
7.82 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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env node
// === Mock Web Socket Server - for testing the topology view
var fs = require('fs'),
readline = require('readline'),
http = require('http'),
WebSocketServer = require('websocket').server,
port = 8123,
scenarioRoot = 'ev/';
var lastcmd, // last command executed
lastargs, // arguments to last command
connection, // ws connection
origin, // origin of connection
scid, // scenario ID
scdata, // scenario data
scdone, // shows when scenario is over
eventsById, // map of event file names
maxEvno, // highest loaded event number
evno, // next event number
evdata; // event data
var scFiles = fs.readdirSync(scenarioRoot);
console.log('Mock Server v1.0');
console.log('================');
console.log('Scenarios ...');
console.log(scFiles.join(', '));
console.log();
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('ws> ');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(port, function() {
console.log((new Date()) + ' Server is listening on port ' + port);
});
server.on('listening', function () {
console.log('OK, server is running');
console.log('(? for help)');
});
var wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
console.log(); // newline after prompt
console.log("Origin: ", request.origin);
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
origin = request.origin;
connection = request.accept(null, origin);
console.log((new Date()) + ' Connection accepted.');
rl.prompt();
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log(); // newline after prompt
console.log('Received Message: ' + message.utf8Data);
//connection.sendUTF(message.utf8Data);
rl.prompt();
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
//connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
connection = null;
origin = null;
});
});
setTimeout(doCli, 10); // allow async processes to write to stdout first
function doCli() {
rl.prompt();
rl.on('line', function (line) {
var words = line.trim().split(' '),
cmd = words.shift(),
str = words.join(' ');
if (!cmd) {
// repeat last command
cmd = lastcmd;
str = lastargs;
}
switch(cmd) {
case 'c': connStatus(); break;
case 'm': customMessage(str); break;
case 's': setScenario(str); break;
case 'n': nextEvent(); break;
case 'r': restartScenario(); break;
case 'q': quit(); break;
case '?': showHelp(); break;
default: console.log('Say what?! (? for help)'); break;
}
lastcmd = cmd;
lastargs = str;
rl.prompt();
}).on('close', function () {
quit();
});
}
var helptext = '\n' +
'c - show connection status\n' +
'm {text} - send custom message to client\n' +
's {id} - load scenario {id}\n' +
's - show scenario staus\n' +
//'a - auto-send events\n' +
'n - send next event\n' +
'r - restart the scenario\n' +
'q - exit the server\n' +
'? - display this help text\n';
function showHelp() {
console.log(helptext);
}
function connStatus() {
if (connection) {
console.log('Connection from ' + origin + ' established.');
} else {
console.log('No connection.');
}
}
function quit() {
console.log('Quitting...');
process.exit(0);
}
function customMessage(m) {
if (connection) {
console.log('Sending message: ' + m);
connection.sendUTF(m);
} else {
console.warn('No current connection.');
}
}
function showScenarioStatus() {
var msg;
if (!scid) {
console.log('No scenario loaded.');
} else {
msg = 'Scenario: "' + scid + '", ' +
(scdone ? 'DONE' : 'next event: ' + evno);
console.log(msg);
}
}
function scenarioPath(evno) {
var file = evno ? ('/' + eventsById[evno].fname) : '/scenario.json';
return scenarioRoot + scid + file;
}
function initScenario(verb) {
console.log(); // get past prompt
console.log(verb + ' scenario "' + scid + '"');
console.log(scdata.title);
scdata.description.forEach(function (d) {
console.log(' ' + d);
});
evno = 1;
scdone = false;
readEventFilenames();
}
function readEventFilenames() {
var files = fs.readdirSync(scenarioRoot + scid),
eventCount = 0,
match, id, tag;
maxEvno = 0;
eventsById = {};
files.forEach(function (f) {
match = /^ev_(\d+)_(.*)\.json$/.exec(f);
if (match) {
eventCount++;
id = match[1];
tag = match[2];
eventsById[id] = {
fname: f,
num: id,
tag: tag
};
if (Number(id) > Number(maxEvno)) {
maxEvno = id;
}
}
});
console.log('[' + eventCount + ' events loaded, (max=' + maxEvno + ')]');
}
function setScenario(id) {
if (!id) {
return showScenarioStatus();
}
evdata = null;
scid = id;
fs.readFile(scenarioPath(), 'utf8', function (err, data) {
if (err) {
console.warn('No scenario named "' + id + '"', err);
scid = null;
} else {
scdata = JSON.parse(data);
initScenario('Loading');
}
rl.prompt();
});
}
function restartScenario() {
if (!scid) {
console.log('No scenario loaded.');
} else {
initScenario('Restarting');
}
rl.prompt();
}
function nextEvent() {
var path;
if (!scid) {
console.log('No scenario loaded.');
rl.prompt();
} else if (!connection) {
console.warn('No current connection.');
rl.prompt();
} else {
if (Number(evno) > Number(maxEvno)) {
// done
scdone = true;
console.log('Scenario DONE.');
} else {
// fire next event
path = scenarioPath(evno);
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
console.log('Oops error: ' + err);
} else {
evdata = JSON.parse(data);
console.log(); // get past prompt
console.log('Sending event #' + evno + ' [' + evdata.event + ']');
connection.sendUTF(data);
evno++;
}
rl.prompt();
});
}
}
}