-
Notifications
You must be signed in to change notification settings - Fork 2
/
dht.js
67 lines (54 loc) · 1.48 KB
/
dht.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
var binding = require('./dht.node');
var DHT = binding.DHT;
var natStr = function(state) {
switch (state) {
default:
case binding.NODE_UNDEFINED:
return "undefined";
case binding.NODE_NAT:
return "nat";
case binding.NODE_CONE:
return "cone";
case binding.NODE_SYMMETRIC:
return "symmetric";
case binding.NODE_GLOBAL:
return "global";
}
}
DHT.prototype.recv = function (fn) {
if (arguments.length != 1)
throw new Error("Requires at least 1 argument (function)");
if (typeof fn != "function")
throw new Error("First argument must be a function");
this._setDgramCallback(fn);
return this;
}
DHT.prototype.send = function (id, buffer) {
if (arguments.length != 2)
throw new Error("Requires at least 2 arguments");
if (typeof id != "string")
throw new Error("First argument must be a string (node id)");
if (! (buffer instanceof Buffer))
throw new Error("Second argument must be a buffer");
this._sendDgram(id, buffer);
return this;
}
DHT.prototype.setGlobal = function () {
this._setGlobal();
this.natState = natStr(this._natState());
return this;
}
DHT.prototype.get = function (key, fn) {
this._get(key, function (success, buffers) {
fn.call(this, success, buffers);
});
return this;
}
function createNode(port, dtun, inet) {
var dht = new DHT();
inet = inet || binding.PF_INET;
dtun = dtun || true;
dht.open(inet, port, dtun);
return dht;
}
module.exports = {createNode: createNode};