diff --git a/lib/client.js b/lib/client.js index e3ca1c2..a24365c 100644 --- a/lib/client.js +++ b/lib/client.js @@ -9,6 +9,25 @@ var BinaryStream = require('./stream').BinaryStream; // end node + +function sequentialStreamId(socket) { + if (!(this instanceof sequentialStreamId)) return new sequentialStreamId(socket); + + if(typeof socket === 'string') { + this._nextId = 0; + } else { + // Use odd numbered ids for server originated streams + this._nextId = 1; + } +} + +sequentialStreamId.prototype.next = function(meta) { + var result = this._nextId; + this._nextId += 2; + + return result; +} + function BinaryClient(socket, options) { if (!(this instanceof BinaryClient)) return new BinaryClient(socket, options); @@ -17,17 +36,18 @@ function BinaryClient(socket, options) { var self = this; this._options = util.extend({ - chunkSize: 40960 + chunkSize: 40960, + streamIdGenerator: sequentialStreamId }, options); this.streams = {}; - + + this.streamIdGenerator = this._options.streamIdGenerator(socket); + if(typeof socket === 'string') { - this._nextId = 0; this._socket = new WebSocket(socket); } else { // Use odd numbered ids for server originated streams - this._nextId = 1; this._socket = socket; } @@ -234,10 +254,10 @@ BinaryClient.prototype.createStream = function(meta){ return; } var self = this; - var streamId = this._nextId; - this._nextId += 2; + var streamId = this.streamIdGenerator.next(meta); + var binaryStream = new BinaryStream(this._socket, streamId, true, meta); - binaryStream.on('close', function(){ + binaryStream.on('close', function(){ delete self.streams[streamId]; }); this.streams[streamId] = binaryStream;