1 | `#!/usr/bin/env node
|
2 | `
|
3 | utils = require "./utils.js"
|
4 | utils.extend global, utils
|
5 |
|
6 | optimist = require "optimist"
|
7 | args = optimist.usage("Usage: $0 [--port=PORT] [--host=ADDRESS] [--sock=PATH] [--mode=MODE]")
|
8 | .alias("h", "help")
|
9 | .default("port", config.port)
|
10 | .default("host", config.host)
|
11 | .default("sock", config.sock)
|
12 | .default("mode", config.mode)
|
13 | .argv
|
14 |
|
15 | if args.help
|
16 | optimist.showHelp()
|
17 | process.exit 0
|
18 |
|
19 | responseHandlers = {}
|
20 | webSock = null
|
21 |
|
22 | WSS = require("ws").Server
|
23 | wss = new WSS port: args.port, host: args.host
|
24 | wss.on "connection", (ws) ->
|
25 | console.log "#{new Date().toString()}: websocket client connected"
|
26 | webSock = ws
|
27 | ws.on "message", (msg) ->
|
28 | responseHandlers[JSON.parse(msg).clientId]? msg
|
29 |
|
30 | uniqueId = Math.floor(2000000000 * Math.random()).toString()
|
31 | clientId = 0
|
32 |
|
33 | handleWebsocketError = (request) ->
|
34 | responseHandlers[request.clientId]? JSON.stringify extend request, error: "websocket is not connected"
|
35 | responseHandlers = {}
|
36 | webSock = null
|
37 |
|
38 | server = require("net").createServer (sock) ->
|
39 | clientId += 1
|
40 | myClientId = "#{uniqueId}-#{clientId}"
|
41 | responseHandlers[myClientId] = sock.write.bind sock
|
42 |
|
43 | sock.on "data", (data) ->
|
44 | try
|
45 | request = JSON.parse data
|
46 | catch
|
47 | console.error "failed to parse JSON: #{data}"
|
48 | try
|
49 | extend request, clientId: myClientId
|
50 | webSock.send JSON.stringify(request), (err) ->
|
51 | handleWebsocketError request if err
|
52 | catch
|
53 | handleWebsocketError request
|
54 |
|
55 | sock.on "close", ->
|
56 | delete responseHandlers[myClientId]
|
57 |
|
58 | require("fs").unlink args.sock, ->
|
59 | server.listen args.sock, ->
|
60 | require("fs").chmod args.sock, args.mode, ->
|
61 | console.log "listening on: #{args.sock}"
|