Last active
August 29, 2015 14:05
-
-
Save myndzi/b9817a415190723d40fb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function Thing(opts) { | |
opts = opts || { }; | |
Duplex.call(this, opts); | |
// not object mode on write (?) | |
this._readableState.objectMode = true; | |
this.upstream = false; | |
this.downstream = false; | |
this.port = opts.port; | |
this.host = opts.host; | |
this.state = 0; | |
this.chunks = [ ]; | |
this.con = new net.Socket(); | |
} | |
Thing.prototype._read = function () { | |
var chunk = true, more = true; | |
// upstream called us, it wants data | |
this.upstream = true; | |
while (chunk && more) { | |
chunk = this.getObject(); | |
if (chunk) { | |
more = this.push(chunk); | |
} | |
} | |
}; | |
Thing.prototype._write = function (chunk, enc, cb) { | |
this.con.write(chunk); | |
cb(); | |
}; | |
Thing.prototype.connect = function (cb) { | |
this.con.connect(self.port, self.host, this.init.bind(this)); | |
}; | |
Thing.prototype.init = function () { | |
// does 'readable' get emitted when the first data is available? | |
this.con.on('readable', this.process.bind(this)); | |
this.con.write('hello'); | |
); | |
Thing.prototype.process = function () { | |
var chunk = true; | |
this.downstream = true; | |
switch (this.state) { | |
case 0: | |
var len = this.con.read(24); | |
if (len === null) { | |
return; | |
} | |
// parse packet | |
state++; | |
break; | |
case 1: | |
while (chunk) { | |
chunk = this.chunks.push(this.read()); | |
} | |
downstream = false; | |
if (this.upstream) { this._read(); } | |
break; | |
} | |
}; | |
Thing.prototype.getObject = function () { | |
// process this.chunks for an object to emit and return it, or return null | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment