Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created December 7, 2012 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/4231520 to your computer and use it in GitHub Desktop.
Save Raynos/4231520 to your computer and use it in GitHub Desktop.

Channel example

A channel consists of two parts. A list of peers in the signalling channel and a network interface to open connections to them.

First you listen to the network, then you wait to hear about peers and then open connections.

For a true peer to peer system you should open connections deterministically, i.e. only one of the peers should connect the other should wait.

var SignalChannel = require("signal-channel")
    , uuid = require("node-uuid")
    , WriteStream = require("write-stream")

    , channel = SignalChannel("unique namespace")
    , peers = channel.createPeers()
    , network = channel.createNetwork(onConnection)
    , id = uuid()

peers.on("join", function (peer) {
    if (peer.id <= id) {
        // other side will open this connection
        return
    }

    onConnection(network.connect(peer.id))
})

network.listen(id)
peers.join({ id: id })

function onConnection(stream) {
    stream.pipe(WriteStream(function (data) {
        console.log("got data", data, "from", stream.peerId)
    }))

    stream.write("some data to" + id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment