WebSocketServer.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. // The Nagle Algorithm makes more efficient use of network resources
  102. // by introducing a small delay before sending small packets so that
  103. // multiple messages can be batched together before going onto the
  104. // wire. This however comes at the cost of latency, so the default
  105. // is to disable it. If you don't need low latency and are streaming
  106. // lots of small messages, you can change this to 'false'
  107. disableNagleAlgorithm: true,
  108. // The number of milliseconds to wait after sending a close frame
  109. // for an acknowledgement to come back before giving up and just
  110. // closing the socket.
  111. closeTimeout: 5000
  112. };
  113. extend(this.config, config);
  114. if (this.config.httpServer) {
  115. if (!Array.isArray(this.config.httpServer)) {
  116. this.config.httpServer = [this.config.httpServer];
  117. }
  118. var upgradeHandler = this._handlers.upgrade;
  119. this.config.httpServer.forEach(function(httpServer) {
  120. httpServer.on('upgrade', upgradeHandler);
  121. });
  122. }
  123. else {
  124. throw new Error('You must specify an httpServer on which to mount the WebSocket server.');
  125. }
  126. };
  127. WebSocketServer.prototype.unmount = function() {
  128. var upgradeHandler = this._handlers.upgrade;
  129. this.config.httpServer.forEach(function(httpServer) {
  130. httpServer.removeListener('upgrade', upgradeHandler);
  131. });
  132. };
  133. WebSocketServer.prototype.closeAllConnections = function() {
  134. this.connections.forEach(function(connection) {
  135. connection.close();
  136. });
  137. this.pendingRequests.forEach(function(request) {
  138. process.nextTick(function() {
  139. request.reject(503); // HTTP 503 Service Unavailable
  140. });
  141. });
  142. };
  143. WebSocketServer.prototype.broadcast = function(data) {
  144. if (Buffer.isBuffer(data)) {
  145. this.broadcastBytes(data);
  146. }
  147. else if (typeof(data.toString) === 'function') {
  148. this.broadcastUTF(data);
  149. }
  150. };
  151. WebSocketServer.prototype.broadcastUTF = function(utfData) {
  152. this.connections.forEach(function(connection) {
  153. connection.sendUTF(utfData);
  154. });
  155. };
  156. WebSocketServer.prototype.broadcastBytes = function(binaryData) {
  157. this.connections.forEach(function(connection) {
  158. connection.sendBytes(binaryData);
  159. });
  160. };
  161. WebSocketServer.prototype.shutDown = function() {
  162. this.unmount();
  163. this.closeAllConnections();
  164. };
  165. WebSocketServer.prototype.handleUpgrade = function(request, socket) {
  166. var wsRequest = new WebSocketRequest(socket, request, this.config);
  167. try {
  168. wsRequest.readHandshake();
  169. }
  170. catch(e) {
  171. wsRequest.reject(
  172. e.httpCode ? e.httpCode : 400,
  173. e.message,
  174. e.headers
  175. );
  176. debug('Invalid handshake: %s', e.message);
  177. return;
  178. }
  179. this.pendingRequests.push(wsRequest);
  180. wsRequest.once('requestAccepted', this._handlers.requestAccepted);
  181. wsRequest.once('requestResolved', this._handlers.requestResolved);
  182. if (!this.config.autoAcceptConnections && utils.eventEmitterListenerCount(this, 'request') > 0) {
  183. this.emit('request', wsRequest);
  184. }
  185. else if (this.config.autoAcceptConnections) {
  186. wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
  187. }
  188. else {
  189. wsRequest.reject(404, 'No handler is configured to accept the connection.');
  190. }
  191. };
  192. WebSocketServer.prototype.handleRequestAccepted = function(connection) {
  193. var self = this;
  194. connection.once('close', function(closeReason, description) {
  195. self.handleConnectionClose(connection, closeReason, description);
  196. });
  197. this.connections.push(connection);
  198. this.emit('connect', connection);
  199. };
  200. WebSocketServer.prototype.handleConnectionClose = function(connection, closeReason, description) {
  201. var index = this.connections.indexOf(connection);
  202. if (index !== -1) {
  203. this.connections.splice(index, 1);
  204. }
  205. this.emit('close', connection, closeReason, description);
  206. };
  207. WebSocketServer.prototype.handleRequestResolved = function(request) {
  208. var index = this.pendingRequests.indexOf(request);
  209. if (index !== -1) { this.pendingRequests.splice(index, 1); }
  210. };
  211. module.exports = WebSocketServer;