-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprotocol.js
59 lines (45 loc) · 1.33 KB
/
protocol.js
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
59
'use strict'
const EventEmitter = require('events')
const debug = require('debug')('socket.io-monitor:protocol')
const { parse, stringify } = require('./parser')
const END_OF_MESSAGE = new Buffer('~~~')
exports.bindSocket = socket => {
const e = new EventEmitter
const emit = e.emit.bind(e)
const read = readMessage(emit)
// Receive message = emit to local event emitter
let buffer = new Buffer('')
socket.on('data', chunk => {
buffer = read(Buffer.concat([buffer, chunk]))
})
// Emit message = send to remote socket
e.emit = (name, data) => {
try {
socket.write(Buffer.concat([ stringify(name, data), END_OF_MESSAGE ]))
} catch (err) {
debug('Serialize error', err)
debug('Serialize error (data)', { name, data })
}
}
return e
}
const readMessage = emit => {
const read = buffer => {
const index = buffer.indexOf(END_OF_MESSAGE)
if (index === -1) {
return buffer
}
const msg = buffer.slice(0, index)
try {
const { name, data } = parse(msg)
emit(name, data)
} catch (err) {
debug('Parse error', err)
debug('Parse error (message)', msg.toString())
}
const rest = buffer.slice(index + END_OF_MESSAGE.length)
// Check for another message, return the rest (beginning of a new message)
return read(rest)
}
return read
}