|
| 1 | +var WebSocketMultiplex = (function(){ |
| 2 | + |
| 3 | + |
| 4 | + // **** |
| 5 | + |
| 6 | + var DumbEventTarget = function() { |
| 7 | + this._listeners = {}; |
| 8 | + }; |
| 9 | + DumbEventTarget.prototype._ensure = function(type) { |
| 10 | + if(!(type in this._listeners)) this._listeners[type] = []; |
| 11 | + }; |
| 12 | + DumbEventTarget.prototype.addEventListener = function(type, listener) { |
| 13 | + this._ensure(type); |
| 14 | + this._listeners[type].push(listener); |
| 15 | + }; |
| 16 | + DumbEventTarget.prototype.emit = function(type) { |
| 17 | + this._ensure(type); |
| 18 | + var args = Array.prototype.slice.call(arguments, 1); |
| 19 | + if(this['on' + type]) this['on' + type].apply(this, args); |
| 20 | + for(var i=0; i < this._listeners[type].length; i++) { |
| 21 | + this._listeners[type][i].apply(this, args); |
| 22 | + } |
| 23 | + }; |
| 24 | + |
| 25 | + |
| 26 | + // **** |
| 27 | + |
| 28 | + var WebSocketMultiplex = function(ws) { |
| 29 | + var that = this; |
| 30 | + this.ws = ws; |
| 31 | + this.channels = {}; |
| 32 | + this.ws.addEventListener('message', function(e) { |
| 33 | + var t = e.data.split(','); |
| 34 | + var type = t.shift(), name = t.shift(), payload = t.join(); |
| 35 | + if(!(name in that.channels)) { |
| 36 | + return; |
| 37 | + } |
| 38 | + var sub = that.channels[name]; |
| 39 | + |
| 40 | + switch(type) { |
| 41 | + case 'uns': |
| 42 | + delete that.channels[name]; |
| 43 | + sub.emit('close', {}); |
| 44 | + break; |
| 45 | + case 'msg': |
| 46 | + sub.emit('message', {data: payload}); |
| 47 | + break; |
| 48 | + } |
| 49 | + }); |
| 50 | + }; |
| 51 | + WebSocketMultiplex.prototype.channel = function(raw_name) { |
| 52 | + return this.channels[escape(raw_name)] = |
| 53 | + new Channel(this.ws, escape(raw_name), this.channels); |
| 54 | + }; |
| 55 | + |
| 56 | + |
| 57 | + var Channel = function(ws, name, channels) { |
| 58 | + DumbEventTarget.call(this); |
| 59 | + var that = this; |
| 60 | + this.ws = ws; |
| 61 | + this.name = name; |
| 62 | + this.channels = channels; |
| 63 | + var onopen = function() { |
| 64 | + that.ws.send('sub,' + that.name); |
| 65 | + that.emit('open'); |
| 66 | + }; |
| 67 | + if(ws.readyState > 0) { |
| 68 | + setTimeout(onopen, 0); |
| 69 | + } else { |
| 70 | + this.ws.addEventListener('open', onopen); |
| 71 | + } |
| 72 | + }; |
| 73 | + Channel.prototype = new DumbEventTarget() |
| 74 | + |
| 75 | + Channel.prototype.send = function(data) { |
| 76 | + this.ws.send('msg,' + this.name + ',' + data); |
| 77 | + }; |
| 78 | + Channel.prototype.close = function() { |
| 79 | + var that = this; |
| 80 | + this.ws.send('uns,' + this.name); |
| 81 | + delete this.channels[this.name]; |
| 82 | + setTimeout(function(){that.emit('close', {});},0); |
| 83 | + }; |
| 84 | + |
| 85 | + return WebSocketMultiplex; |
| 86 | +})(); |
0 commit comments