forked from nknorg/nkn-client-js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode_example.js
64 lines (59 loc) · 1.83 KB
/
node_example.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
// Example of nkn-client-js for Node.js
// Usage: node node_example.js
const crypto = require('crypto');
const nkn = require('../lib/nkn');
const timeout = 5000;
var timeSent, timeReceived;
function generateMessage() {
let fromClient = nkn({
// neither of these are required, as shown in toClient below
identifier: crypto.randomBytes(8).toString('hex'),
privateKey: 'cd5fa29ed5b0e951f3d1bce5997458706186320f1dd89156a73d54ed752a7f37',
});
fromClient.on('connect', () => {
try {
let toClient = nkn();
toClient.on('connect', () => {
try {
fromClient.send(
toClient.addr,
'This is a generated message.',
).then(() => {
timeReceived = new Date();
console.log('Receive ACK from', toClient.addr, 'after', timeReceived - timeSent, 'ms');
}).catch((e) => {
console.log('Catch: ', e);
});
timeSent = new Date();
console.log('Send message from', fromClient.addr, 'to', toClient.addr);
setTimeout(function () {
try {
toClient.close();
if (timeReceived === undefined) {
console.log('Message from', fromClient.nodeAddr, 'to', toClient.nodeAddr, 'timeout');
}
} catch (e) {
console.error(e);
}
}, timeout);
} catch (e) {
console.error(e);
}
});
toClient.on('message', (src, payload) => {
timeReceived = new Date();
console.log('Receive message from', src, 'after', timeReceived - timeSent, 'ms');
});
setTimeout(function () {
try {
fromClient.close();
} catch (e) {
console.error(e);
}
}, timeout);
} catch (e) {
console.error(e);
}
});
}
generateMessage();