Skip to content

Instantly share code, notes, and snippets.

@st3b1t
Last active June 16, 2024 12:00
Show Gist options
  • Save st3b1t/228de794aeca35f371682a3dae9b3a83 to your computer and use it in GitHub Desktop.
Save st3b1t/228de794aeca35f371682a3dae9b3a83 to your computer and use it in GitHub Desktop.
websocket p2p network in nodejs
/*
PART OF: https://github.com/st3b1t/libp2p-nodejs-playground
setup:
$ npm install libp2p @chainsafe/libp2p-noise @chainsafe/libp2p-yamux @libp2p/bootstrap @libp2p/mdns @libp2p/websockets
run:
$ node libp2p_websocket.js <PORT>
open in more terminal with different port
*/
import { createLibp2p } from 'libp2p'
import { webSockets } from '@libp2p/websockets'
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
//import { bootstrap } from '@libp2p/bootstrap'
import { mdns } from '@libp2p/mdns' //Multicast DNS
//env DEBUG="libp2p:tcp,libp2p:websockets,libp2p:webtransport,libp2p:kad-dht,libp2p:dialer"
const port = Number(process.argv[2]) || 8000;
(async() => {
const node = await createLibp2p({
start: false,
addresses: {
listen: [`/ip4/127.0.0.1/tcp/${port}/ws`]
},
transports: [
webSockets()
],
connectionEncryption: [noise()],
streamMuxers: [yamux()],
peerDiscovery: [
mdns()
]
});
node.addEventListener('peer:discovery', e => {
console.log('New peer Discovered', e.detail.id)
})
node.addEventListener('peer:connect', e => {
console.log('Connected to peer:', e.detail)
})
await node.start()
const listenAddrs = node.getMultiaddrs();
console.log('node listen: ', listenAddrs)
process.on('SIGINT', async () => {
console.log('node stopping...');
await node.stop()
process.exit(0);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment