From 25cde57edad27cc0e7450d7090d77568e3569393 Mon Sep 17 00:00:00 2001 From: Shay Erlichmen Date: Sun, 21 Apr 2013 12:31:30 +0300 Subject: [PATCH] New option to control the stream id generation New server option to control the generation of the stream id, the default behaviour is incrementing numbers (odds for server side stream, even for client side stream) but for all kinds of proposes you might want to control how those ids are generated. --- lib/client.js | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) 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;