Proxy p2p connections using a duplex stream and Hyperswarm
How it works
- A server initializes an instance of hyperswarm
- A client opens a connection to the server (use any duplex stream)
- Client instance behaves the same as hyperswarm
- The client asks to join "topics"
- The server starts searching for peers and sends peer information to the client
- The client chooses which peers to connect to (all of them by default)
- The server establishes a connection to the peer and proxies it over to the client
- The client can relay whatever data they want to the peer.
const HyperswarmProxyServer =const server =// The bootstrap nodes to pass to hyperswarm (optional)bootstrap// Whether your server will be sort lived (ephemeral: true)ephemeral// Pass in an existing hyperswarm instance instead of creating a new one (optional)network// Function that takes incoming connections to decide what to do with them// Can be used to notify clients about peers// Disconnect incoming by defaultsocketconst somestream =// Get the server to handle streams from clientsserver// Tell all clients about a peer for a particular topic// This is useful in conjunction with `handleIncoming`// Use handleIncoming to figure out which topic the connection is from// Then tell clients to connect to them using `socket.address()`server// Close connections to clients and any connected peersserver
const HyperswarmProxyClient =const somestream =const swarm =// Pass in the stream which connects to the server// If this isn't passed in, invoke `.reconnect(somestream)` to start connectingconnection: somestream// Whether you should autoconnect to peersautoconnect: true// The max number of peers to connect to before stopping to autoconnectmaxPeers: 24// When we disconnect, reconnect to the serverswarm// Same as hyperswarmswarmswarmswarm// Listen for peers manuallyswarm// Destroy the swarmswarm