Created
November 13, 2012 08:34
-
-
Save Raynos/4064668 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* WebRTC consist of a few moving pieces | |
- A signal mechanism for peers | |
- A signal mechanism to send offers & answers | |
- A simplified peerConnection function | |
*/ | |
var uuid = require("node-uuid") | |
, equal = require("assert").equal | |
, WriteStream = require("write-stream") | |
, extract = require("extract") | |
, Peers = require("peers-signal") | |
, PeerConnection = require("peer-connection") | |
, id = uuid() | |
, peers = Peers("discoverynetwork.co/service" | |
, "unique group name") | |
, connectionHash = {} | |
peers.on("create", function handlePeer(peer) { | |
if (peer.id < self.id) { | |
// Other peer will open the connection | |
return | |
} | |
var stream = connect(peer) | |
// Connected peer is an echo stream | |
stream.pipe(WriteStream(function (message) { | |
equal(message, "hello world") | |
})) | |
stream.write("hello world") | |
}) | |
var self = peers.add({ id: id }) | |
listen(peers, self, function (stream) { | |
// I am an echo stream | |
stream.pipe(stream) | |
}) | |
function connect(peer) { | |
var pc = connectionHash[peer.id] = PeerConnection() | |
pc.createOffer(function (err, offer) { | |
peer.emit("offer", [self.id, offer]) | |
}) | |
return pc.connect() | |
} | |
function listen(peers, self, callback) { | |
self.on("offer", extract(function (id, offer) { | |
var pc = connectionHash[id] = PeerConnection() | |
pc.setRemote(offer) | |
pc.createAnswer(function (err, answer) { | |
peers.get(id).emit("answer", [self.id, answer]) | |
pc.on("connection", callback) | |
}) | |
})) | |
self.on("answer", extract(function (id, answer) { | |
var pc = connectionHash[id] | |
pc.setRemote(answer) | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment