WebSocketRouter.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 util = require('util');
  18. var EventEmitter = require('events').EventEmitter;
  19. var WebSocketRouterRequest = require('./WebSocketRouterRequest');
  20. function WebSocketRouter(config) {
  21. // Superclass Constructor
  22. EventEmitter.call(this);
  23. this.config = {
  24. // The WebSocketServer instance to attach to.
  25. server: null
  26. };
  27. if (config) {
  28. extend(this.config, config);
  29. }
  30. this.handlers = [];
  31. this._requestHandler = this.handleRequest.bind(this);
  32. if (this.config.server) {
  33. this.attachServer(this.config.server);
  34. }
  35. }
  36. util.inherits(WebSocketRouter, EventEmitter);
  37. WebSocketRouter.prototype.attachServer = function(server) {
  38. if (server) {
  39. this.server = server;
  40. this.server.on('request', this._requestHandler);
  41. }
  42. else {
  43. throw new Error('You must specify a WebSocketServer instance to attach to.');
  44. }
  45. };
  46. WebSocketRouter.prototype.detachServer = function() {
  47. if (this.server) {
  48. this.server.removeListener('request', this._requestHandler);
  49. this.server = null;
  50. }
  51. else {
  52. throw new Error('Cannot detach from server: not attached.');
  53. }
  54. };
  55. WebSocketRouter.prototype.mount = function(path, protocol, callback) {
  56. if (!path) {
  57. throw new Error('You must specify a path for this handler.');
  58. }
  59. if (!protocol) {
  60. protocol = '____no_protocol____';
  61. }
  62. if (!callback) {
  63. throw new Error('You must specify a callback for this handler.');
  64. }
  65. path = this.pathToRegExp(path);
  66. if (!(path instanceof RegExp)) {
  67. throw new Error('Path must be specified as either a string or a RegExp.');
  68. }
  69. var pathString = path.toString();
  70. // normalize protocol to lower-case
  71. protocol = protocol.toLocaleLowerCase();
  72. if (this.findHandlerIndex(pathString, protocol) !== -1) {
  73. throw new Error('You may only mount one handler per path/protocol combination.');
  74. }
  75. this.handlers.push({
  76. 'path': path,
  77. 'pathString': pathString,
  78. 'protocol': protocol,
  79. 'callback': callback
  80. });
  81. };
  82. WebSocketRouter.prototype.unmount = function(path, protocol) {
  83. var index = this.findHandlerIndex(this.pathToRegExp(path).toString(), protocol);
  84. if (index !== -1) {
  85. this.handlers.splice(index, 1);
  86. }
  87. else {
  88. throw new Error('Unable to find a route matching the specified path and protocol.');
  89. }
  90. };
  91. WebSocketRouter.prototype.findHandlerIndex = function(pathString, protocol) {
  92. protocol = protocol.toLocaleLowerCase();
  93. for (var i=0, len=this.handlers.length; i < len; i++) {
  94. var handler = this.handlers[i];
  95. if (handler.pathString === pathString && handler.protocol === protocol) {
  96. return i;
  97. }
  98. }
  99. return -1;
  100. };
  101. WebSocketRouter.prototype.pathToRegExp = function(path) {
  102. if (typeof(path) === 'string') {
  103. if (path === '*') {
  104. path = /^.*$/;
  105. }
  106. else {
  107. path = path.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  108. path = new RegExp('^' + path + '$');
  109. }
  110. }
  111. return path;
  112. };
  113. WebSocketRouter.prototype.handleRequest = function(request) {
  114. var requestedProtocols = request.requestedProtocols;
  115. if (requestedProtocols.length === 0) {
  116. requestedProtocols = ['____no_protocol____'];
  117. }
  118. // Find a handler with the first requested protocol first
  119. for (var i=0; i < requestedProtocols.length; i++) {
  120. var requestedProtocol = requestedProtocols[i].toLocaleLowerCase();
  121. // find the first handler that can process this request
  122. for (var j=0, len=this.handlers.length; j < len; j++) {
  123. var handler = this.handlers[j];
  124. if (handler.path.test(request.resourceURL.pathname)) {
  125. if (requestedProtocol === handler.protocol ||
  126. handler.protocol === '*')
  127. {
  128. var routerRequest = new WebSocketRouterRequest(request, requestedProtocol);
  129. handler.callback(routerRequest);
  130. return;
  131. }
  132. }
  133. }
  134. }
  135. // If we get here we were unable to find a suitable handler.
  136. request.reject(404, 'No handler is available for the given request.');
  137. };
  138. module.exports = WebSocketRouter;