UNPKG

2.36 kBJavaScriptView Raw
1#!/usr/bin/env node
2;
3var WSS, args, clientId, handleWebsocketError, optimist, responseHandlers, server, uniqueId, utils, webSock, wss;
4
5utils = require("./utils.js");
6
7utils.extend(global, utils);
8
9optimist = require("optimist");
10
11args = optimist.usage("Usage: $0 [--port=PORT] [--host=ADDRESS] [--sock=PATH] [--mode=MODE]").alias("h", "help")["default"]("port", config.port)["default"]("host", config.host)["default"]("sock", config.sock)["default"]("mode", config.mode).argv;
12
13if (args.help) {
14 optimist.showHelp();
15 process.exit(0);
16}
17
18responseHandlers = {};
19
20webSock = null;
21
22WSS = require("ws").Server;
23
24wss = new WSS({
25 port: args.port,
26 host: args.host
27});
28
29wss.on("connection", function(ws) {
30 console.log((new Date().toString()) + ": websocket client connected");
31 webSock = ws;
32 return ws.on("message", function(msg) {
33 var name;
34 return typeof responseHandlers[name = JSON.parse(msg).clientId] === "function" ? responseHandlers[name](msg) : void 0;
35 });
36});
37
38uniqueId = Math.floor(2000000000 * Math.random()).toString();
39
40clientId = 0;
41
42handleWebsocketError = function(request) {
43 var name;
44 if (typeof responseHandlers[name = request.clientId] === "function") {
45 responseHandlers[name](JSON.stringify(extend(request, {
46 error: "websocket is not connected"
47 })));
48 }
49 responseHandlers = {};
50 return webSock = null;
51};
52
53server = require("net").createServer(function(sock) {
54 var myClientId;
55 clientId += 1;
56 myClientId = uniqueId + "-" + clientId;
57 responseHandlers[myClientId] = sock.write.bind(sock);
58 sock.on("data", function(data) {
59 var request;
60 try {
61 request = JSON.parse(data);
62 } catch (_error) {
63 console.error("failed to parse JSON: " + data);
64 }
65 try {
66 extend(request, {
67 clientId: myClientId
68 });
69 return webSock.send(JSON.stringify(request), function(err) {
70 if (err) {
71 return handleWebsocketError(request);
72 }
73 });
74 } catch (_error) {
75 return handleWebsocketError(request);
76 }
77 });
78 return sock.on("close", function() {
79 return delete responseHandlers[myClientId];
80 });
81});
82
83require("fs").unlink(args.sock, function() {
84 return server.listen(args.sock, function() {
85 return require("fs").chmod(args.sock, args.mode, function() {
86 return console.log("listening on: " + args.sock);
87 });
88 });
89});