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)
My naive attempt at multiplexing/demultiplexing Scuttlebutt Model streams.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.