This repository has been archived by the owner on Aug 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraft.js
71 lines (65 loc) · 1.85 KB
/
raft.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
60
61
62
63
64
65
66
67
68
69
70
71
const url = require('url');
const debug = require('diagnostics')('socketio:raftadapter:transport');
const LifeRaft = require('liferaft');
const net = require('net');
const notepack = require('notepack.io');
//
// Create a custom Raft instance which uses a plain TCP server and client to
// communicate back and forth.
//
module.exports = class TCPRaft extends LifeRaft {
/**
* Initialized, start connecting all the things.
*
* @param {Object} options Options.
* @api private
*/
initialize (options) {
const server = net.createServer((socket) => {
socket.on('data', buff => {
var data = JSON.parse(buff.toString());
debug(this.address +':packet#received', data);
this.emit('data', data, data => {
debug(this.address +':packet#reply', data);
const encoded = notepack.encode(data);
socket.write(encoded);
socket.end();
});
});
}).listen(options.address);
this.once('end', function enc() {
server.close();
});
}
/**
* The message to write.
*
* @TODO implement indefinitely sending of packets.
* @param {Object} packet The packet to write to the connection.
* @param {Function} fn Completion callback.
* @api private
*/
write (packet, fn) {
let socket;
try {
const addressURL = new url.URL(this.address);
socket = net.connect({host: addressURL.hostname, port: addressURL.port});
} catch (e) {
fn(e);
return;
}
debug(this.address + ':packet#write', packet);
socket.on('error', fn);
socket.on('data', buff => {
try {
const decoded = notepack.decode(buff);
debug(this.address + ':packet#callback', decoded);
fn(undefined, decoded);
} catch (e) {
fn(e);
}
});
socket.setNoDelay(true);
socket.write(JSON.stringify(packet));
}
}