-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtcpTransport.coffee
More file actions
39 lines (32 loc) · 1.06 KB
/
tcpTransport.coffee
File metadata and controls
39 lines (32 loc) · 1.06 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
net = require 'net'
class tcpTransport
constructor: (@params) ->
if !@params
throw new Error 'emptyParams'
send: (body, callback) ->
client = net.connect @params, ->
client.write JSON.stringify body
client.on 'error', (e) ->
callback e, null if callback
client.on 'timeout', ->
callback new Error('TimeoutError'), null if callback
client.end()
client.on 'data', (data) ->
callback null, data.toString() if callback
client.end()
close: () ->
if @tcpServer
@tcpServer.close()
listen: (server) ->
@tcpServer = net.createServer (socket) ->
socket.on 'error', -> socket.end()
socket.on 'data', (data) ->
ip = socket.remoteAddress || '127.0.0.1'
ip = ip.replace('::ffff:', '')
server.handleCall data.toString(), {client_ip: ip}, (answer) ->
socket.write JSON.stringify answer if answer
if @params.path?
@tcpServer.listen @params.path
else
@tcpServer.listen @params.port
module.exports = tcpTransport