1 | #!/usr/bin/env node
|
2 | ;
|
3 | var WSS, args, clientId, handleWebsocketError, optimist, responseHandlers, server, uniqueId, utils, webSock, wss;
|
4 |
|
5 | utils = require("./utils.js");
|
6 |
|
7 | utils.extend(global, utils);
|
8 |
|
9 | optimist = require("optimist");
|
10 |
|
11 | args = 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 |
|
13 | if (args.help) {
|
14 | optimist.showHelp();
|
15 | process.exit(0);
|
16 | }
|
17 |
|
18 | responseHandlers = {};
|
19 |
|
20 | webSock = null;
|
21 |
|
22 | WSS = require("ws").Server;
|
23 |
|
24 | wss = new WSS({
|
25 | port: args.port,
|
26 | host: args.host
|
27 | });
|
28 |
|
29 | wss.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 |
|
38 | uniqueId = Math.floor(2000000000 * Math.random()).toString();
|
39 |
|
40 | clientId = 0;
|
41 |
|
42 | handleWebsocketError = 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 |
|
53 | server = 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 |
|
83 | require("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 | });
|