forked from telehash/telehash-js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
talk.js
98 lines (86 loc) · 1.81 KB
/
talk.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var telehash = require("../index.js").telehash;
var stdin = process.openStdin();
stdin.setEncoding("UTF-8");
//throw away output to stderr - required nodejs v0.6+
process.__defineGetter__('stderr', function () {
return {
write: function () {}
};
});
var connector;
var chatCache = {};
var me;
var friend;
me = process.argv[2];
friend = process.argv[3];
if (!me && !friend) {
console.log("Usage: node talk @you @friend");
process.exit();
}
telehash.init(function (err) {
if (err) return;
telehash.seed(function (status, info) {
if (status === 'offline' && info === 'snat-detected') {
console.log("SNAT detected. Exiting...");
process.exit();
}
if (status !== "online") {
console.log(status);
return;
}
if (!connector) {
stdin.on('data', function (chunk) {
if (chunk.length > 1) {
SendTxt(chunk);
}
});
}
talk();
});
});
function talk() {
console.log("connecting to:", friend);
if (!connector) {
connector = telehash.connect(friend);
listen(me);
console.log("we are:", me);
}
SendTxt('[CONNECTED]');
}
function listen(name) {
telehash.listen(name, function (obj) {
obj.reply({
ack: 1
}); //ACK the message
if (!chatCache[obj.message.txt]) {
chatCache[obj.message.txt] = 1;
console.log("<<--:", obj.message.txt);
}
});
}
function SendTxt(txt) {
if (!connector) return;
var gotResponse = false;
connector.send({
txt: txt
}, function (obj) {
if (obj) {
if (obj.message.ack) gotResponse = true;
if (obj.count == 1) console.log("-->>:", txt);
} else {
if (!gotResponse) {
setTimeout(function () {
SendTxt(txt);
}, 100);
}
}
}, 5); //timeout after 5 seconds.
}
stdin.on('end', function () {
if (this.exiting) return;
this.exiting = true;
if (connector) connector.send({
txt: '[DISCONNECTED]'
});
telehash.shutdown();
});