Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created November 20, 2012 08:00
Show Gist options
  • Save Raynos/4116665 to your computer and use it in GitHub Desktop.
Save Raynos/4116665 to your computer and use it in GitHub Desktop.
var WriteStream = require("write-stream")
, uuid = require("node-uuid")
, assert = require("assert")
// to be implemented
, PeerConnectionPool = require("peer-connection-pool")
, PeerConnection = require("peer-connection-shim")
// to be implemented
, Peers = require("peer-nodes")
, reconnect = require("reconnect/sockjs")
// connect to the signal channel
connect("signalchannel.co", function (peers, pool) {
var id = uuid()
// Listen to the pool on your own identifier.
// For each new incoming connection just echo back their data
pool.listen(id).on("connection", function (stream) {
stream.pipe(stream)
})
// For each new peer, open a connection to them and see
// whether they echo it back
peers.on("join", function (peer) {
var stream = pool.connect(peer.id)
stream.pipe(WriteStream(function onwrite(message) {
assert.equal(message, "hello world")
}))
stream.write("hello world")
})
// Join the peer network
peers.join({
id: id
})
})
function connect(uri, callback) {
// Connect to the remote sockJS server which acts as a
// signal channel and a relay server
reconnect(function (stream) {
// Multiplex the connection due to sockJS limitation
// Open up three streams for peer list replication,
// signal channel for the pool & and the relay stream
// for the peer connection shim
var mdm = MuxDemux()
, peerStream = mdm.createStream("/v1/scuttlebutt")
, poolStream = mdm.createStream("/v1/echo")
, relayStream = mdm.createStream("/v1/relay")
, peers = Peers()
// Pass the pool a function which generates a new
// PeerConnection. In this case use the shim but in
// the future just use webrtc
, pool = PeerConnectionPool(function () {
return PeerConnection({
stream: relayStream
})
})
// pump the streams up
peerStream.pipe(peers.createStream()).pipe(peerStream)
poolStream.pipe(pool.createStream()).pipe(poolStream)
stream.pipe(mdm).pipe(stream)
// pass peers & pool to callback
callback(peers, pool)
}).listen(uri)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment