Skip to content

Instantly share code, notes, and snippets.

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 dominictarr/5111698 to your computer and use it in GitHub Desktop.
Save dominictarr/5111698 to your computer and use it in GitHub Desktop.
fix a few common stream/scuttlebutt gotchas
var MuxDemux = require('mux-demux');
var net = require('net');
var Model = require('scuttlebutt/model');
var aModel = new Model
var bModel = new Model
//the scuttlebutt's must have 1 stream per connection,
//therefore they must be created inside the server handler.
// Server
var server = new net.createServer(function (stream) {
var mx = new MuxDemux
mx.pipe(stream).pipe(mx)
//the server side should listen on 'connect'
mx.on('connection', function(stream) {
if (stream.meta === 'channel1') {
//scuttlebutt does a handshake, even if you only update one side.
//so, you have to connect it duplex style.
stream.pipe(aModel.createStream()).pipe(stream)
}
else if (stream.meta === 'channel2') {
stream.pipe(bModel.createStream()).pipe(stream)
}
})
}).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 dModel = new Model
server.on('listening', function() {
//the client stream does not need to be piped inside the callback.
//when creating a new connection, any messages are buffered.
var stream = net.connect(8000)
var mx = new MuxDemux
mx.pipe(stream).pipe(mx)
//use createStream - this creates a two way (duplex) stream
//always use createStream when you pipe duplex style (a.pipe(b).pipe(a))
var channel1 = mx.createStream('channel1')
var channel2 = mx.createStream('channel2')
channel1.pipe(cModel.createStream()).pipe(channel1)
channel2.pipe(dModel.createStream()).pipe(channel2)
//you only need mx.on('connection',...) on one side...
})
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment