-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathnode_example.js
85 lines (80 loc) · 2.9 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Example of nkn-client-js for Node.js
// Usage: node node_example.js seedRpcServerAddr timeoutInMilliSeconds
const crypto = require('crypto');
const nkn = require('../lib/nkn');
// Never put private key in version control system like here!
const seed = '2bc5501d131696429264eb7286c44a29dd44dd66834d9471bd8b0eb875a1edb0';
const seedRpcServerAddr = process.argv[2];
const timeout = parseInt(process.argv[3]) || 5000;
const logPrefix = process.argv[4] ? ('[' + process.argv[4] + '] ') : '';
var timeSent, timeReceived;
function generateMessage() {
let fromClient = nkn({
// neither of these are required, as shown in toClient below
identifier: crypto.randomBytes(8).toString('hex'),
seed: seed,
seedRpcServerAddr: seedRpcServerAddr,
});
fromClient.on('connect', () => {
try {
let toClient = nkn({
identifier: crypto.randomBytes(8).toString('hex'),
seedRpcServerAddr: seedRpcServerAddr,
});
toClient.on('connect', () => {
try {
fromClient.send(
toClient.addr,
'Hello world!',
// For byte array:
// Uint8Array.from([1,2,3,4,5]),
).then((data) => {
timeReceived = new Date();
console.log(logPrefix + 'Receive', '"' + data + '"', 'from', toClient.addr, 'after', timeReceived - timeSent, 'ms');
}).catch((e) => {
console.log(logPrefix + 'Catch: ', e);
});
timeSent = new Date();
console.log(logPrefix + 'Send message from', fromClient.addr, 'to', toClient.addr);
setTimeout(function () {
try {
toClient.close();
if (timeReceived === undefined) {
console.log(logPrefix + 'Message from', fromClient.nodeAddr, 'to', toClient.nodeAddr, 'timeout');
}
} catch (e) {
console.error(logPrefix + e);
}
}, timeout);
} catch (e) {
console.error(logPrefix + e);
}
});
// can also be async (src, payload, payloadType) => {}
toClient.on('message', (src, payload, payloadType, encrypt) => {
timeReceived = new Date();
var type;
if (payloadType === nkn.PayloadType.TEXT) {
type = 'text';
} else if (payloadType === nkn.PayloadType.BINARY) {
type = 'binary';
}
console.log(logPrefix + 'Receive', encrypt ? 'encrypted' : 'unencrypted', type, 'message', '"' + payload + '"','from', src, 'after', timeReceived - timeSent, 'ms');
// Send a text response
return 'Well received!';
// For byte array response:
// return Uint8Array.from([1,2,3,4,5])
});
setTimeout(function () {
try {
fromClient.close();
} catch (e) {
console.error(logPrefix + e);
}
}, timeout);
} catch (e) {
console.error(logPrefix + e);
}
});
}
generateMessage();