I am trying to send a message from one connected node server to the other using the following code in server.js
and server1.js
:
const hyperswarm = require('hyperswarm')
const crypto = require('crypto')
const swarm = hyperswarm()
// look for peers listed under this topic
const topic = crypto.createHash('sha256')
.update('mycoolstuff')
.digest()
swarm.join(topic, {
lookup: true, // find & connect to peers
announce: true // optional- announce self as a connection target
})
swarm.on('connection', (socket, details) => {
//console.log('new connection!', details)
// you can now use the socket as a stream, eg:
process.stdin.pipe(socket).pipe(process.stdout)
})
The problem is the message from one terminal is duplicated on the other.
For example, if I type the following in server.js's terminal:
test 123
I get the following in server1.js's:
test 123
test 123
. . . and vice versa
I can work around this by setting one of the two servers to not announce:
swarm.join(topic, {
lookup: true, // find & connect to peers
announce: false // <--------- don't announce, stops duplicates
})
But I would prefer that both servers announce.
What am I misunderstanding about sockets, stdin, or hyperswarm here?
Well, I found my own answer inside the node module folder for hyperswarm in the file called example.js
I added the following:
const {
priority,
status,
retries,
peer,
client
} = details
if (client) process.stdin.pipe(socket)
else socket.pipe(process.stdout)
Which solved my problem.