-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket.coffee
58 lines (47 loc) · 1.14 KB
/
socket.coffee
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
net = require 'net'
socket_id = 0
sockets = {}
callbacks = {}
create = (type, options, callback) ->
if type != 'tcp'
throw Error("Not Implemented: #{type}")
callback
socketId: ++socket_id
connect = (socketId, host, port, callback) ->
client = net.connect port, host
client.on 'data', (data) ->
on_read = client.on_read
client.on_read = undefined
if on_read?
on_read
resultCode: 1
data: data
else
console.log 'read dropped', client
client.on 'close', ->
console.log 'closing socket!'
sockets[socketId] = client
callback client # TODO: should pass an interger
read = (socketId, bufferSize, callback) ->
if bufferSize != null
throw Error("Not Implemented")
client = sockets[socketId]
client.on_read = callback
write = (socketId, data, callback) ->
client = sockets[socketId]
buffer = new Buffer data.byteLength
array = new Uint8Array data
for i in [0...buffer.length]
buffer[i] = array[i]
client.write buffer, null, ->
callback
resultCode: 1
disconnect = (socketId) ->
client = sockets[socketId]
client.end()
module.exports =
create: create
connect: connect
read: read
write: write
disconnect: disconnect