3 var Emitter = require('events').EventEmitter,
4 util = require('util'),
5 streams = require('../streams'),
6 Headers = require('./headers'),
7 Reader = require('./stream_reader');
9 var Base = function(request, url, options) {
11 Base.validateOptions(options || {}, ['maxLength', 'masking', 'requireMasking', 'protocols']);
13 this._request = request;
14 this._reader = new Reader();
15 this._options = options || {};
16 this._maxLength = this._options.maxLength || this.MAX_LENGTH;
17 this._headers = new Headers();
22 this.io = new streams.IO(this);
23 this.messages = new streams.Messages(this);
24 this._bindEventListeners();
26 util.inherits(Base, Emitter);
28 Base.validateOptions = function(options, validKeys) {
29 for (var key in options) {
30 if (validKeys.indexOf(key) < 0)
31 throw new Error('Unrecognized option: ' + key);
36 // This is 64MB, small enough for an average VPS to handle without
37 // crashing from process out of memory
38 MAX_LENGTH: 0x3ffffff,
40 STATES: ['connecting', 'open', 'closing', 'closed'],
42 _bindEventListeners: function() {
45 // Protocol errors are informational and do not have to be handled
46 this.messages.on('error', function() {});
48 this.on('message', function(event) {
49 var messages = self.messages;
50 if (messages.readable) messages.emit('data', event.data);
53 this.on('error', function(error) {
54 var messages = self.messages;
55 if (messages.readable) messages.emit('error', error);
58 this.on('close', function() {
59 var messages = self.messages;
60 if (!messages.readable) return;
61 messages.readable = messages.writable = false;
66 getState: function() {
67 return this.STATES[this.readyState] || null;
70 addExtension: function(extension) {
74 setHeader: function(name, value) {
75 if (this.readyState > 0) return false;
76 this._headers.set(name, value);
81 if (this.readyState !== 0) return false;
82 var response = this._handshakeResponse();
83 if (!response) return false;
84 this._write(response);
85 if (this._stage !== -1) this._open();
89 text: function(message) {
90 return this.frame(message);
93 binary: function(message) {
105 close: function(reason, code) {
106 if (this.readyState !== 1) return false;
108 this.emit('close', new Base.CloseEvent(null, null));
114 this.__queue.forEach(function(args) { this.frame.apply(this, args) }, this);
116 this.emit('open', new Base.OpenEvent());
119 _queue: function(message) {
120 this.__queue.push(message);
124 _write: function(chunk) {
126 if (io.readable) io.emit('data', chunk);
130 for (var key in instance)
131 Base.prototype[key] = instance[key];
134 Base.ConnectEvent = function() {};
136 Base.OpenEvent = function() {};
138 Base.CloseEvent = function(code, reason) {
140 this.reason = reason;
143 Base.MessageEvent = function(data) {
147 module.exports = Base;