1 | WebSocketServer = require('websocket').server
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | class WebSocketRuntime
|
7 | constructor: (@options = {}) ->
|
8 | @connections = []
|
9 |
|
10 | send: (protocol, topic, payload, context) ->
|
11 | if !context.connection or !context.connection.connected
|
12 | return
|
13 | if topic == 'error' and payload instanceof Error
|
14 | payload =
|
15 | message: payload.message
|
16 | stack: payload.stack
|
17 | context.connection.sendUTF JSON.stringify(
|
18 | protocol: protocol
|
19 | command: topic
|
20 | payload: payload)
|
21 | return
|
22 |
|
23 | sendAll: (protocol, topic, payload, context) ->
|
24 | if topic == 'error' and payload instanceof Error
|
25 | payload =
|
26 | message: payload.message
|
27 | stack: payload.stack
|
28 | @connections.forEach (connection) ->
|
29 | connection.sendUTF JSON.stringify(
|
30 | protocol: protocol
|
31 | command: topic
|
32 | payload: payload)
|
33 | return
|
34 | return
|
35 |
|
36 | module.exports = (httpServer, options) ->
|
37 | wsServer = new WebSocketServer(httpServer: httpServer)
|
38 | runtime = new WebSocketRuntime(options)
|
39 |
|
40 | handleMessage = (message, connection) ->
|
41 | if message.type == 'utf8'
|
42 | contents = undefined
|
43 | try
|
44 | contents = JSON.parse(message.utf8Data)
|
45 | catch e
|
46 | if e.stack
|
47 | console.error e.stack
|
48 | else
|
49 | console.error 'Error: ' + e.toString()
|
50 | return
|
51 | runtime.receive contents.protocol, contents.command, contents.payload, connection: connection
|
52 |
|
53 | wsServer.on 'request', (request) ->
|
54 | subProtocol = if request.requestedProtocols.indexOf('noflo') != -1 then 'noflo' else null
|
55 | connection = request.accept(subProtocol, request.origin)
|
56 | runtime.connections.push connection
|
57 | connection.on 'message', (message) ->
|
58 | handleMessage message, connection
|
59 | connection.on 'close', ->
|
60 | return if runtime.connections.indexOf(connection) == -1
|
61 | runtime.connections.splice runtime.connections.indexOf(connection), 1
|
62 |
|
63 | return runtime
|
64 |
|
65 |
|