websocket.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // API references:
  2. //
  3. // * https://html.spec.whatwg.org/multipage/comms.html#network
  4. // * https://dom.spec.whatwg.org/#interface-eventtarget
  5. // * https://dom.spec.whatwg.org/#interface-event
  6. 'use strict';
  7. var util = require('util'),
  8. driver = require('websocket-driver'),
  9. API = require('./websocket/api');
  10. var WebSocket = function(request, socket, body, protocols, options) {
  11. options = options || {};
  12. this._stream = socket;
  13. this._driver = driver.http(request, { maxLength: options.maxLength, protocols: protocols });
  14. var self = this;
  15. if (!this._stream || !this._stream.writable) return;
  16. if (!this._stream.readable) return this._stream.end();
  17. var catchup = function() { self._stream.removeListener('data', catchup) };
  18. this._stream.on('data', catchup);
  19. API.call(this, options);
  20. process.nextTick(function() {
  21. self._driver.start();
  22. self._driver.io.write(body);
  23. });
  24. };
  25. util.inherits(WebSocket, API);
  26. WebSocket.isWebSocket = function(request) {
  27. return driver.isWebSocket(request);
  28. };
  29. WebSocket.validateOptions = function(options, validKeys) {
  30. driver.validateOptions(options, validKeys);
  31. };
  32. WebSocket.WebSocket = WebSocket;
  33. WebSocket.Client = require('./websocket/client');
  34. WebSocket.EventSource = require('./eventsource');
  35. module.exports = WebSocket;