Skip to content

Instantly share code, notes, and snippets.

@mjohnsullivan
Created March 7, 2013 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mjohnsullivan/5109842 to your computer and use it in GitHub Desktop.
Save mjohnsullivan/5109842 to your computer and use it in GitHub Desktop.
My naive attempt at multiplexing/demultiplexing Scuttlebutt Model streams.
var MuxDemux = require('mux-demux');
var net = require('net');
var Model = require('scuttlebutt/model');
var aModel = new Model
var aModelStream = aModel.createStream()
var bModel = new Model
var bModelStream = bModel.createStream()
// Server
var server = new net.createServer(function (stream) {
var mx = new MuxDemux
mx.pipe(stream).pipe(mx)
var channel1 = mx.createStream('channel1')
var channel2 = mx.createStream('channel2')
aModelStream.pipe(channel1)
bModelStream.pipe(channel2)
mx.on('connection', function(stream) {
if (stream.meta === 'channel1') {
stream.pipe(aModelStream)
}
else if (stream.meta === 'channel2') {
stream.pipe(bModelStream)
}
})
}).listen(8000)
aModel.on('update', function(data) {
console.log('A updated with: ' + JSON.stringify(data))
})
bModel.on('update', function(data) {
console.log('B updated with: ' + JSON.stringify(data))
})
// Client
var cModel = new Model
var cModelStream = cModel.createStream()
var dModel = new Model
var dModelStream = dModel.createStream()
server.on('listening', function() {
var stream = net.connect(8000, function() {
var mx = new MuxDemux
mx.pipe(stream).pipe(mx)
var channel1 = mx.createWriteStream('channel1')
var channel2 = mx.createWriteStream('channel2')
cModelStream.pipe(channel1)
dModelStream.pipe(channel2)
mx.on('connection', function(stream) {
if (stream.meta === 'channel1') {
stream.pipe(cModelStream)
}
else if (stream.meta === 'channel2') {
stream.pipe(dModelStream)
}
})
})
})
cModel.on('update', function(data) {
console.log('C updated with: ' + JSON.stringify(data))
})
dModel.on('update', function(data) {
console.log('D updated with: ' + JSON.stringify(data))
})
setTimeout(function() {
aModel.set('bob', {a: 'valuea'})
}, 1000)
setTimeout(function() {
bModel.set('bob', {b: 'valueb'})
}, 2000)
setTimeout(function() {
cModel.set('bob', {c: 'valuec'})
}, 3000)
setTimeout(function() {
dModel.set('bob', {d: 'valued'})
}, 4000)
@dominictarr
Copy link

there are a few small mistakes here, I've fixed them in my fork.
https://gist.github.com/dominictarr/5111698

basically,

  • create the scuttlebutt streams inside the server handler
  • scuttlebutt is used duplex style pipe: a.pipe(b).pipe(a)
  • use mx.on('connection',...) on one side, and mx.createStream(...) on the other
  • always use mx.createStream() for duplex, not mx.createWriteStream()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment