Browse Source

update to take a key and add a distinctive message

ameba23 2 years ago
parent
commit
c556fc27f7
2 changed files with 14 additions and 17 deletions
  1. 11
    14
      index.js
  2. 3
    3
      test/index.test.js

+ 11
- 14
index.js View File

@@ -1,17 +1,16 @@
1 1
 const createStream = require('broadcast-stream')
2
+const distinctiveKey = Buffer.from('peer2peerforeverpeer2peerforever') // 32 bytes
2 3
 
3 4
 const PORT = 8999
4 5
 const INTERVAL = 1000 // probably to short, but good for trying it out
5 6
 
6 7
 module.exports = { broadcast, receive }
7 8
 
8
-function broadcast (msg, opts = {}) {
9
+function broadcast (key, opts = {}) {
9 10
   const port = opts.port || PORT
10 11
   const stream = createStream(port)
11 12
 
12
-  // Some defining message, eg: hash of the word cobox
13
-  // and a hash to replicate on
14
-  msg = msg || Buffer.from('cobox replicator over here', 'utf8')
13
+  const msg = Buffer.concat([distinctiveKey, key])
15 14
   const interval = opts.inverval || INTERVAL
16 15
 
17 16
   const destroy = setInterval(() => {
@@ -24,21 +23,19 @@ function broadcast (msg, opts = {}) {
24 23
   }
25 24
 }
26 25
 
27
-function receive (callback, opts = {}) {
26
+function receive (foundKey, opts = {}) {
28 27
   const port = opts.port || PORT
29 28
   const stream = createStream(port)
30 29
   const foundMsgs = []
31 30
 
32 31
   stream.on('data', (msg) => {
33
-    // console.log(msg.toString())
34
-    // console.log(msg.address, msg.port, msg.loopback, msg.echo)
35
-
36
-    // TODO: check for some defining feature
37
-    // if (checkdefiningfeature...)
38
-    const checkMessage = msg.toString('hex') + msg.address
39
-    if (!foundMsgs.includes(checkMessage)) {
40
-      foundMsgs.push(checkMessage)
41
-      callback(msg)
32
+    if (msg.slice(0, 32).toString() === distinctiveKey.toString()) {
33
+      const key = msg.slice(32, msg.length)
34
+      const checkMessage = key.toString('hex') + msg.address // do we care about ip address?
35
+      if (!foundMsgs.includes(checkMessage)) {
36
+        foundMsgs.push(checkMessage)
37
+        foundKey(key)
38
+      }
42 39
     }
43 40
   })
44 41
 

+ 3
- 3
test/index.test.js View File

@@ -1,12 +1,12 @@
1 1
 const { describe } = require('tape-plus')
2 2
 const { broadcast, receive } = require('..')
3
-const message = Buffer.from('boop')
3
+const key = Buffer.from('1c3b02755089674b89704d51303af05ad1f57a4acf7774c5b884792a77acf024', 'hex')
4 4
 
5 5
 describe('basic', (context) => {
6 6
   context('broadcast and receive', (assert, next) => {
7
-    const destroyBroadcast = broadcast(message, { interval: 1000 })
7
+    const destroyBroadcast = broadcast(key, { interval: 1000 })
8 8
     const destroyReceive = receive((msg) => {
9
-      assert.same(msg, message, 'received the message that was broadcast')
9
+      assert.same(msg, key, 'received the key that was broadcast')
10 10
     })
11 11
 
12 12
     setTimeout(() => {