Browse Source

broadcast and recieve functions

ameba23 2 years ago
parent
commit
76a2d84f0a
1 changed files with 36 additions and 9 deletions
  1. 36
    9
      index.js

+ 36
- 9
index.js View File

@@ -1,12 +1,39 @@
1
-var createStream = require('broadcast-stream')
1
+const createStream = require('broadcast-stream')
2 2
 
3
-var stream = createStream(8999)
3
+const PORT = 8999
4
+const INTERVAL = 1000
4 5
 
5
-stream.on('data', function (msg) {
6
-  console.log(msg.toString())
7
-  console.log(msg.address, msg.port, msg.loopback, msg.echo)
8
-})
6
+module.exports = { broadcast, recieve }
9 7
 
10
-setInterval(function () {
11
-  stream.write(Buffer.from('cobox replicator over here', 'utf8'))
12
-}, 1000)
8
+function broadcast (msg, opts = {}) {
9
+  const port = opts.port || PORT
10
+  const stream = createStream(port)
11
+
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')
15
+  const interval = opts.inverval || INTERVAL
16
+
17
+  setInterval(() => {
18
+    stream.write(msg)
19
+  }, interval)
20
+}
21
+
22
+function recieve (callback, opts = {}) {
23
+  const port = opts.port || PORT
24
+  const stream = createStream(port)
25
+  const foundMsgs = []
26
+
27
+  stream.on('data', (msg) => {
28
+    // console.log(msg.toString())
29
+    // console.log(msg.address, msg.port, msg.loopback, msg.echo)
30
+
31
+    // TODO: check for some defining feature
32
+    // if (checkdefiningfeature...)
33
+    const checkMessage = msg.toString('hex') + msg.address
34
+    if (!foundMsgs.includes(checkMessage)) {
35
+      foundMsgs.push(checkMessage)
36
+      callback(msg)
37
+    }
38
+  })
39
+}