WebSocketServer.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /************************************************************************
  2. * Copyright 2010-2015 Brian McKelvey.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. ***********************************************************************/
  16. var extend = require('./utils').extend;
  17. var utils = require('./utils');
  18. var util = require('util');
  19. var debug = require('debug')('websocket:server');
  20. var EventEmitter = require('events').EventEmitter;
  21. var WebSocketRequest = require('./WebSocketRequest');
  22. var WebSocketServer = function WebSocketServer(config) {
  23. // Superclass Constructor
  24. EventEmitter.call(this);
  25. this._handlers = {
  26. upgrade: this.handleUpgrade.bind(this),
  27. requestAccepted: this.handleRequestAccepted.bind(this),
  28. requestResolved: this.handleRequestResolved.bind(this)
  29. };
  30. this.connections = [];
  31. this.pendingRequests = [];
  32. if (config) {
  33. this.mount(config);
  34. }
  35. };
  36. util.inherits(WebSocketServer, EventEmitter);
  37. WebSocketServer.prototype.mount = function(config) {
  38. this.config = {
  39. // The http server instance to attach to. Required.
  40. httpServer: null,
  41. // 64KiB max frame size.
  42. maxReceivedFrameSize: 0x10000,
  43. // 1MiB max message size, only applicable if
  44. // assembleFragments is true
  45. maxReceivedMessageSize: 0x100000,
  46. // Outgoing messages larger than fragmentationThreshold will be
  47. // split into multiple fragments.
  48. fragmentOutgoingMessages: true,
  49. // Outgoing frames are fragmented if they exceed this threshold.
  50. // Default is 16KiB
  51. fragmentationThreshold: 0x4000,
  52. // If true, the server will automatically send a ping to all
  53. // clients every 'keepaliveInterval' milliseconds. The timer is
  54. // reset on any received data from the client.
  55. keepalive: true,
  56. // The interval to send keepalive pings to connected clients if the
  57. // connection is idle. Any received data will reset the counter.
  58. keepaliveInterval: 20000,
  59. // If true, the server will consider any connection that has not
  60. // received any data within the amount of time specified by
  61. // 'keepaliveGracePeriod' after a keepalive ping has been sent to
  62. // be dead, and will drop the connection.
  63. // Ignored if keepalive is false.
  64. dropConnectionOnKeepaliveTimeout: true,
  65. // The amount of time to wait after sending a keepalive ping before
  66. // closing the connection if the connected peer does not respond.
  67. // Ignored if keepalive is false.
  68. keepaliveGracePeriod: 10000,
  69. // Whether to use native TCP keep-alive instead of WebSockets ping
  70. // and pong packets. Native TCP keep-alive sends smaller packets
  71. // on the wire and so uses bandwidth more efficiently. This may
  72. // be more important when talking to mobile devices.
  73. // If this value is set to true, then these values will be ignored:
  74. // keepaliveGracePeriod
  75. // dropConnectionOnKeepaliveTimeout
  76. useNativeKeepalive: false,
  77. // If true, fragmented messages will be automatically assembled
  78. // and the full message will be emitted via a 'message' event.
  79. // If false, each frame will be emitted via a 'frame' event and
  80. // the application will be responsible for aggregating multiple
  81. // fragmented frames. Single-frame messages will emit a 'message'
  82. // event in addition to the 'frame' event.
  83. // Most users will want to leave this set to 'true'
  84. assembleFragments: true,
  85. // If this is true, websocket connections will be accepted
  86. // regardless of the path and protocol specified by the client.
  87. // The protocol accepted will be the first that was requested
  88. // by the client. Clients from any origin will be accepted.
  89. // This should only be used in the simplest of cases. You should
  90. // probably leave this set to 'false' and inspect the request
  91. // object to make sure it's acceptable before accepting it.
  92. autoAcceptConnections: false,
  93. // Whether or not the X-Forwarded-For header should be respected.
  94. // It's important to set this to 'true' when accepting connections
  95. // from untrusted clients, as a malicious client could spoof its
  96. // IP address by simply setting this header. It's meant to be added
  97. // by a trusted proxy or other intermediary within your own
  98. // infrastructure.
  99. // See: http://en.wikipedia.org/wiki/X-Forwarded-For
  100. ignoreXForwardedFor: false,
  101. // If this is true, 'cookie' headers are parsed and exposed as WebSocketRequest.cookies
  102. parseCookies: true,
  103. // If this is true, 'sec-websocket-extensions' headers are parsed and exposed as WebSocketRequest.requestedExtensions
  104. parseExtensions: true,
  105. // The Nagle Algorithm makes more efficient use of network resources
  106. // by introducing a small delay before sending small packets so that
  107. // multiple messages can be batched together before going onto the
  108. // wire. This however comes at the cost of latency, so the default
  109. // is to disable it. If you don't need low latency and are streaming
  110. // lots of small messages, you can change this to 'false'
  111. disableNagleAlgorithm: true,
  112. // The number of milliseconds to wait after sending a close frame
  113. // for an acknowledgement to come back before giving up and just
  114. // closing the socket.
  115. closeTimeout: 5000
  116. };
  117. extend(this.config, config);
  118. if (this.config.httpServer) {
  119. if (!Array.isArray(this.config.httpServer)) {
  120. this.config.httpServer = [this.config.httpServer];
  121. }
  122. var upgradeHandler = this._handlers.upgrade;
  123. this.config.httpServer.forEach(function(httpServer) {
  124. httpServer.on('upgrade', upgradeHandler);
  125. });
  126. }
  127. else {
  128. throw new Error('You must specify an httpServer on which to mount the WebSocket server.');
  129. }
  130. };
  131. WebSocketServer.prototype.unmount = function() {
  132. var upgradeHandler = this._handlers.upgrade;
  133. this.config.httpServer.forEach(function(httpServer) {
  134. httpServer.removeListener('upgrade', upgradeHandler);
  135. });
  136. };
  137. WebSocketServer.prototype.closeAllConnections = function() {
  138. this.connections.forEach(function(connection) {
  139. connection.close();
  140. });
  141. this.pendingRequests.forEach(function(request) {
  142. process.nextTick(function() {
  143. request.reject(503); // HTTP 503 Service Unavailable
  144. });
  145. });
  146. };
  147. WebSocketServer.prototype.broadcast = function(data) {
  148. if (Buffer.isBuffer(data)) {
  149. this.broadcastBytes(data);
  150. }
  151. else if (typeof(data.toString) === 'function') {
  152. this.broadcastUTF(data);
  153. }
  154. };
  155. WebSocketServer.prototype.broadcastUTF = function(utfData) {
  156. this.connections.forEach(function(connection) {
  157. connection.sendUTF(utfData);
  158. });
  159. };
  160. WebSocketServer.prototype.broadcastBytes = function(binaryData) {
  161. this.connections.forEach(function(connection) {
  162. connection.sendBytes(binaryData);
  163. });
  164. };
  165. WebSocketServer.prototype.shutDown = function() {
  166. this.unmount();
  167. this.closeAllConnections();
  168. };
  169. WebSocketServer.prototype.handleUpgrade = function(request, socket) {
  170. var self = this;
  171. var wsRequest = new WebSocketRequest(socket, request, this.config);
  172. try {
  173. wsRequest.readHandshake();
  174. }
  175. catch(e) {
  176. wsRequest.reject(
  177. e.httpCode ? e.httpCode : 400,
  178. e.message,
  179. e.headers
  180. );
  181. debug('Invalid handshake: %s', e.message);
  182. this.emit('upgradeError', e);
  183. return;
  184. }
  185. this.pendingRequests.push(wsRequest);
  186. wsRequest.once('requestAccepted', this._handlers.requestAccepted);
  187. wsRequest.once('requestResolved', this._handlers.requestResolved);
  188. socket.once('close', function () {
  189. self._handlers.requestResolved(wsRequest);
  190. });
  191. if (!this.config.autoAcceptConnections && utils.eventEmitterListenerCount(this, 'request') > 0) {
  192. this.emit('request', wsRequest);
  193. }
  194. else if (this.config.autoAcceptConnections) {
  195. wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
  196. }
  197. else {
  198. wsRequest.reject(404, 'No handler is configured to accept the connection.');
  199. }
  200. };
  201. WebSocketServer.prototype.handleRequestAccepted = function(connection) {
  202. var self = this;
  203. connection.once('close', function(closeReason, description) {
  204. self.handleConnectionClose(connection, closeReason, description);
  205. });
  206. this.connections.push(connection);
  207. this.emit('connect', connection);
  208. };
  209. WebSocketServer.prototype.handleConnectionClose = function(connection, closeReason, description) {
  210. var index = this.connections.indexOf(connection);
  211. if (index !== -1) {
  212. this.connections.splice(index, 1);
  213. }
  214. this.emit('close', connection, closeReason, description);
  215. };
  216. WebSocketServer.prototype.handleRequestResolved = function(request) {
  217. var index = this.pendingRequests.indexOf(request);
  218. if (index !== -1) { this.pendingRequests.splice(index, 1); }
  219. };
  220. module.exports = WebSocketServer;