pax_global_header 0000666 0000000 0000000 00000000064 14035643615 0014521 g ustar 00root root 0000000 0000000 52 comment=a2cd3065167668a9685db0d5f9c4083e8a1839f0 WebSocket-Node-1.0.34/ 0000775 0000000 0000000 00000000000 14035643615 0014357 5 ustar 00root root 0000000 0000000 WebSocket-Node-1.0.34/.github/ 0000775 0000000 0000000 00000000000 14035643615 0015717 5 ustar 00root root 0000000 0000000 WebSocket-Node-1.0.34/.github/workflows/ 0000775 0000000 0000000 00000000000 14035643615 0017754 5 ustar 00root root 0000000 0000000 WebSocket-Node-1.0.34/.github/workflows/websocket-tests.yml 0000664 0000000 0000000 00000000413 14035643615 0023623 0 ustar 00root root 0000000 0000000 name: websocket-tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/setup-node@v1 with: node-version: 10.x - uses: actions/checkout@v2 - run: npm install - run: npm run test WebSocket-Node-1.0.34/.gitignore 0000664 0000000 0000000 00000000165 14035643615 0016351 0 ustar 00root root 0000000 0000000 node_modules/ .DS_Store .lock-* build/ builderror.log npm-debug.log test/autobahn/reports*/* test/scripts/heapdump/* WebSocket-Node-1.0.34/.jshintrc 0000664 0000000 0000000 00000013275 14035643615 0016214 0 ustar 00root root 0000000 0000000 { // JSHint Default Configuration File (as on JSHint website) // See http://jshint.com/docs/ for more details "maxerr" : 50, // {int} Maximum error before stopping // Enforcing "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.) "camelcase" : false, // true: Identifiers must be in camelCase "curly" : true, // true: Require {} for every new block or scope "eqeqeq" : true, // true: Require triple equals (===) for comparison "freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc. "forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty() "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` "latedef" : "nofunc", // true: Require variables/functions to be defined before being used "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` "noempty" : true, // true: Prohibit use of empty blocks "nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters. "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment) "plusplus" : false, // true: Prohibit use of `++` & `--` "quotmark" : "single", // Quotation mark consistency: // false : do nothing (default) // true : ensure whatever is used is consistent // "single" : require single quotes // "double" : require double quotes "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) "unused" : "vars", // vars: Require all defined variables be used, ignore function params "strict" : false, // true: Requires all functions run in ES5 Strict Mode "maxparams" : false, // {int} Max number of formal params allowed per function "maxdepth" : false, // {int} Max depth of nested blocks (within functions) "maxstatements" : false, // {int} Max number statements per function "maxcomplexity" : false, // {int} Max cyclomatic complexity per function "maxlen" : false, // {int} Max number of characters per line // Relaxing "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) "boss" : false, // true: Tolerate assignments where comparisons would be expected "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. "eqnull" : false, // true: Tolerate use of `== null` "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`) "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) // (ex: `for each`, multiple try/catch, function expression…) "evil" : false, // true: Tolerate use of `eval` and `new Function()` "expr" : false, // true: Tolerate `ExpressionStatement` as Programs "funcscope" : false, // true: Tolerate defining variables inside control statements "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') "iterator" : false, // true: Tolerate using the `__iterator__` property "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block "laxbreak" : false, // true: Tolerate possibly unsafe line breakings "laxcomma" : false, // true: Tolerate comma-first style coding "loopfunc" : false, // true: Tolerate functions being defined in loops "multistr" : false, // true: Tolerate multi-line strings "noyield" : false, // true: Tolerate generator functions with no yield statement in them. "notypeof" : false, // true: Tolerate invalid typeof operator values "proto" : false, // true: Tolerate using the `__proto__` property "scripturl" : false, // true: Tolerate script-targeted URLs "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` "sub" : true, // true: Tolerate using `[]` notation when it can still be expressed in dot notation "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` "validthis" : false, // true: Tolerate using this in a non-constructor function // Environments "browser" : true, // Web Browser (window, document, etc) "browserify" : true, // Browserify (node.js code in the browser) "couch" : false, // CouchDB "devel" : true, // Development/debugging (alert, confirm, etc) "dojo" : false, // Dojo Toolkit "jasmine" : false, // Jasmine "jquery" : false, // jQuery "mocha" : false, // Mocha "mootools" : false, // MooTools "node" : true, // Node.js "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) "prototypejs" : false, // Prototype and Scriptaculous "qunit" : false, // QUnit "rhino" : false, // Rhino "shelljs" : false, // ShellJS "worker" : false, // Web Workers "wsh" : false, // Windows Scripting Host "yui" : false, // Yahoo User Interface // Custom Globals "globals" : { // additional predefined global variables "WebSocket": true } } WebSocket-Node-1.0.34/.npmignore 0000664 0000000 0000000 00000000165 14035643615 0016360 0 ustar 00root root 0000000 0000000 .npmignore .gitignore .git/ .DS_Store .lock-* node_modules/ docs/ example/ build/ builderror.log npm-debug.log test/ WebSocket-Node-1.0.34/.npmrc 0000664 0000000 0000000 00000000023 14035643615 0015472 0 ustar 00root root 0000000 0000000 package-lock=false WebSocket-Node-1.0.34/CHANGELOG.md 0000664 0000000 0000000 00000037512 14035643615 0016200 0 ustar 00root root 0000000 0000000 Changelog ========= Version 1.0.34 -------------- *Released 2021-04-14* * Updated browser shim to use the native `globalThis` property when available. See [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) for context. Resolves [#415](https://github.com/theturtle32/WebSocket-Node/issues/415) Version 1.0.33 -------------- *Released 2020-12-08* * Added new configuration options to WebSocketServer allowing implementors to bypass parsing WebSocket extensions and HTTP Cookies if they are not needed. (Thanks, [@aetheon](https://github.com/aetheon)) * Added new `upgradeError` event to WebSocketServer to allow for visibility into and logging of any parsing errors that might occur during the HTTP Upgrade phase. (Thanks, [@aetheon](https://github.com/aetheon)) Version 1.0.32 -------------- *Released 2020-08-28* * Refactor to use [N-API modules](https://nodejs.org/api/n-api.html) from [ws project](https://github.com/websockets). (Thanks, [@andreek](https://github.com/andreek)) * Specifically: * [utf-8-validate](https://github.com/websockets/utf-8-validate) * [bufferutil](https://github.com/websockets/bufferutil) * Removed some documentation notations about very old browsers and very old Websocket protocol drafts that are no longer relevant today in 2020. * Removed outdated notations and instructions about building native extensions, since those functions are now delegated to dependencies. * Add automated unit test executionn via Github Actions (Thanks, [@nebojsa94](https://github.com/nebojsa94)) * Accept new connection close code `1015` ("TLS Handshake"). (More information at the [WebSocket Close Code Number Registry](https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number)) Version 1.0.31 -------------- *Released 2019-12-06* * Fix [infinite loop in error handling](https://github.com/theturtle32/WebSocket-Node/issues/329) (Thanks, [@apirila](https://github.com/apirila)) * Fix [memory leak with multiple WebSocket servers on the same HTTP server](https://github.com/theturtle32/WebSocket-Node/pull/339) (Thanks, [@nazar-pc](https://github.com/nazar-pc)) * [Use es5-ext/global as a more robust way to resolve browser's window object](https://github.com/theturtle32/WebSocket-Node/pull/362) (Thanks, [@michaelsbradleyjr](https://github.com/michaelsbradleyjr)) * [adding compatibility with V8 release greater than v7.6 (node and electron engines)](https://github.com/theturtle32/WebSocket-Node/pull/376) (Thanks, [@artynet](https://github.com/artynet)) Version 1.0.30 -------------- *Released 2019-09-12* * Moved gulp back to devDependencies Version 1.0.29 -------------- *Released 2019-07-03* * Updated some dependencies and updated the .gitignore and .npmignore files Version 1.0.28 -------------- *Released 2018-09-19* * Updated to latest version of [nan](https://github.com/nodejs/nan) Version 1.0.27 -------------- *Released 2018-09-19* * Allowing additional request `headers` to be specified in the `tlsOptions` config parameter for WebSocketClient. See pull request #323 * Resolving deprecation warnings relating to usage of `new Buffer` Version 1.0.26 -------------- *Released 2018-04-27* * No longer using the deprecated `noAssert` parameter for functions reading and writing binary numeric data. (Thanks, [@BridgeAR](https://github.com/BridgeAR)) Version 1.0.25 -------------- *Released 2017-10-18* * Bumping minimum supported node version specified in package.json to v0.10.x because some upstream libraries no longer install on v0.8.x * [Allowing use of close codes 1012, 1013, 1014](https://www.iana.org/assignments/websocket/websocket.xml) * [Allowing the `Host` header to be overridden.](https://github.com/theturtle32/WebSocket-Node/pull/291) (Thanks, [@Juneil](https://github.com/Juneil)) * [Mitigating infinite loop for broken connections](https://github.com/theturtle32/WebSocket-Node/pull/289) (Thanks, [@tvkit](https://github.com/tvkit)) * [Fixed Markdown Typos](https://github.com/theturtle32/WebSocket-Node/pull/281) (Thanks, [@teramotodaiki](https://github.com/teramotodaiki)) * [Adding old readyState constants for W3CWebSocket interface](https://github.com/theturtle32/WebSocket-Node/pull/282) (Thanks, [@thechriswalker](https://github.com/thechriswalker)) Version 1.0.24 -------------- *Released 2016-12-28* * Fixed a bug when using native keepalive on Node >= 6.0. (Thanks, [@prossin](https://github.com/prossin)) * Upgrading outdated dependencies Version 1.0.23 -------------- *Released 2016-05-18* * Official support for Node 6.x * Updating dependencies. Specifically, updating nan to ^2.3.3 Version 1.0.22 -------------- *Released 2015-09-28* * Updating to work with nan 2.x Version 1.0.21 -------------- *Released 2015-07-22* * Incremented and re-published to work around an aborted npm publish of v1.0.20. Version 1.0.20 -------------- *Released 2015-07-22* * Added EventTarget to the W3CWebSocket interface (Thanks, [@ibc](https://github.com/ibc)!) * Corrected an inaccurate error message. (Thanks, [@lekoaf](https://github.com/lekoaf)!) Version 1.0.19 -------------- *Released 2015-05-28* * Updated to nan v1.8.x (tested with v1.8.4) * Added `"license": "Apache-2.0"` to package.json via [pull request #199](https://github.com/theturtle32/WebSocket-Node/pull/199) by [@pgilad](https://github.com/pgilad). See [npm1k.org](http://npm1k.org/). Version 1.0.18 -------------- *Released 2015-03-19* * Resolves [issue #195](https://github.com/theturtle32/WebSocket-Node/pull/179) - passing number to connection.send() causes crash * [Added close code/reason arguments to W3CWebSocket#close()](https://github.com/theturtle32/WebSocket-Node/issues/184) Version 1.0.17 -------------- *Released 2015-01-17* * Resolves [issue #179](https://github.com/theturtle32/WebSocket-Node/pull/179) - Allow toBuffer to work with empty data Version 1.0.16 -------------- *Released 2015-01-16* * Resolves [issue #178](https://github.com/theturtle32/WebSocket-Node/issues/178) - Ping Frames with no data Version 1.0.15 -------------- *Released 2015-01-13* * Resolves [issue #177](https://github.com/theturtle32/WebSocket-Node/issues/177) - WebSocketClient ignores options unless it has a tlsOptions property Version 1.0.14 -------------- *Released 2014-12-03* * Resolves [issue #173](https://github.com/theturtle32/WebSocket-Node/issues/173) - To allow the W3CWebSocket interface to accept an optional non-standard configuration object as its third parameter, which will be ignored when running in a browser context. Version 1.0.13 -------------- *Released 2014-11-29* * Fixes [issue #171](https://github.com/theturtle32/WebSocket-Node/issues/171) - Code to prevent calling req.accept/req.reject multiple times breaks sanity checks in req.accept Version 1.0.12 -------------- *Released 2014-11-28* * Fixes [issue #170](https://github.com/theturtle32/WebSocket-Node/issues/170) - Non-native XOR implementation broken after making JSHint happy Version 1.0.11 -------------- *Released 2014-11-25* * Fixes some undefined behavior surrounding closing WebSocket connections and more reliably handles edge cases. * Adds an implementation of the W3C WebSocket API for browsers to facilitate sharing code between client and server via browserify. (Thanks, [@ibc](https://github.com/ibc)!) * `WebSocketConnection.prototype.close` now accepts optional `reasonCode` and `description` parameters. * Calling `accept` or `reject` more than once on a `WebSocketRequest` will now throw an error. [Issue #149](https://github.com/theturtle32/WebSocket-Node/issues/149) * Handling connections dropped by client before accepted by server [Issue #167](https://github.com/theturtle32/WebSocket-Node/issues/167) * Integrating Gulp and JSHint (Thanks, [@ibc](https://github.com/ibc)!) * Starting to add individual unit tests (using substack's [tape](github.com/substack/tape) and [faucet](github.com/substack/faucet)) Version 1.0.10 -------------- *Released 2014-10-22* * Fixed Issue [#146](https://github.com/theturtle32/WebSocket-Node/issues/146) that was causing WebSocketClient to throw errors when instantiated if passed `tlsOptions`. Version 1.0.9 ------------- *Released 2014-10-20* * Fixing an insidious corner-case bug that prevented `WebSocketConnection` from firing the `close` event in certain cases when there was an error on the underlying `Socket`, leading to connections sticking around forever, stuck erroneously in the `connected` state. These "ghost" connections would cause an error event when trying to write to them. * Removed deprecated `websocketVersion` property. Use `webSocketVersion` instead (case difference). * Allowing user to specify all properties for `tlsOptions` in WebSocketClient, not just a few whitelisted properties. This keeps us from having to constantly add new config properties for new versions of Node. (Thanks, [jesusprubio](https://github.com/jesusprubio)) * Removing support for Node 0.4.x and 0.6.x. * Adding `fuzzingclient.json` spec file for the Autobahn Test Suite. * Now more fairly emitting `message` events from the `WebSocketConnection`. Previously, all buffered frames for a connection would be processed and all `message` events emitted before moving on to processing the next connection with available data. Now We process one frame per connection (most of the time) in a more fair round-robin fashion. * Now correctly calling the `EventEmitter` superclass constructor during class instance initialization. * `WebSocketClient.prototype.connect` now accepts the empty string (`''`) to mean "no subprotocol requested." Previously either `null` or an empty array (`[]`) was required. * Fixing a `TypeError` bug in `WebSocketRouter` (Thanks, [a0000778](https://github.com/a0000778)) * Fixing a potential race condition when attaching event listeners to the underlying `Socket`. (Thanks [RichardBsolut](https://github.com/RichardBsolut)) * `WebSocketClient` now accepts an optional options hash to be passed to `(http|https).request`. (Thanks [mildred](https://github.com/mildred) and [aus](https://github.com/aus)) This enables the following new abilities, amongst others: * Use WebSocket-Node from behind HTTP/HTTPS proxy servers using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar. * Specify the local port and local address to bind the outgoing request socket to. * Adding option to ignore `X-Forwarded-For` headers when accepting connections from untrusted clients. * Adding ability to mount a `WebSocketServer` instance to an arbitrary number of Node http/https servers. * Adding browser shim so Browserify won't blow up when trying to package up code that uses WebSocket-Node. The shim is a no-op, it ***does not implement a wrapper*** providing the WebSocket-Node API in the browser. * Incorporating upstream enhancements for the native C++ UTF-8 validation and xor masking functions. (Thanks [einaros](https://github.com/einaros) and [kkoopa](https://github.com/kkoopa)) Version 1.0.8 ------------- *Released 2012-12-26* * Fixed remaining naming inconsistency of "websocketVersion" as opposed to "webSocketVersion" throughout the code, and added deprecation warnings for use of the old casing throughout. * Fixed an issue with our case-insensitive handling of WebSocket subprotocols. Clients that requested a mixed-case subprotocol would end up failing the connection when the server accepted the connection, returning a lower-case version of the subprotocol name. Now we return the subprotocol name in the exact casing that was requested by the client, while still maintaining the case-insensitive verification logic for convenience and practicality. * Making sure that any socket-level activity timeout that may have been set on a TCP socket is removed when initializing a connection. * Added support for native TCP Keep-Alive instead of using the WebSocket ping/pong packets to serve that function. * Fixed cookie parsing to be compliant with RFC 2109 Version 1.0.7 ------------- *Released 2012-08-12* * ***Native modules are now optional!*** If they fail to compile, WebSocket-Node will still work but will not verify that received UTF-8 data is valid, and xor masking/unmasking of payload data for security purposes will not be as efficient as it is performed in JavaScript instead of native code. * Reduced Node.JS version requirement back to v0.6.10 Version 1.0.6 ------------- *Released 2012-05-22* * Now requires Node v0.6.13 since that's the first version that I can manage to successfully build the native UTF-8 validator with node-gyp through npm. Version 1.0.5 ------------- *Released 2012-05-21* * Fixes the issues that users were having building the native UTF-8 validator on Windows platforms. Special Thanks to: * [zerodivisi0n](https://github.com/zerodivisi0n) * [andreasbotsikas](https://github.com/andreasbotsikas) * Fixed accidental global variable usage (Thanks, [hakobera](https://github.com/hakobera)!) * Added callbacks to the send* methods that provide notification of messages being sent on the wire and any socket errors that may occur when sending a message. (Thanks, [zerodivisi0n](https://github.com/zerodivisi0n)!) * Added option to disable logging in the echo-server in the test folder (Thanks, [oberstet](https://github.com/oberstet)!) Version 1.0.4 ------------- *Released 2011-12-18* * Now validates that incoming UTF-8 messages do, in fact, contain valid UTF-8 data. The connection is dropped with prejudice if invalid data is received. This strict behavior conforms to the WebSocket RFC and is verified by the Autobahn Test Suite. This is accomplished in a performant way by using a native C++ Node module created by [einaros](https://github.com/einaros). * Updated handling of connection closure to pass more of the Autobahn Test Suite. Version 1.0.3 ------------- *Released 2011-12-18* * Substantial speed increase (~150% on my machine, depending on the circumstances) due to an optimization in FastBufferList.js that drastically reduces the number of memory alloctions and buffer copying. ([kazuyukitanimura](https://github.com/kazuyukitanimura)) Version 1.0.2 ------------- *Released 2011-11-28* * Fixing whiteboard example to work under Node 0.6.x ([theturtle32](https://github.com/theturtle32)) * Now correctly emitting a `close` event with a 1006 error code if there is a TCP error while writing to the socket during the handshake. ([theturtle32](https://github.com/theturtle32)) * Catching errors when writing to the TCP socket during the handshake. ([justoneplanet](https://github.com/justoneplanet)) * No longer outputting console.warn messages when there is an error writing to the TCP socket ([justoneplanet](https://github.com/justoneplanet)) * Fixing some formatting errors, commas, semicolons, etc. ([kaisellgren](https://github.com/kaisellgren)) Version 1.0.1 ------------- *Released 2011-11-21* * Now works with Node 0.6.2 as well as 0.4.12 * Support TLS in WebSocketClient * Added support for setting and reading cookies * Added WebSocketServer.prototype.broadcast(data) convenience method * Added `resourceURL` property to WebSocketRequest objects. It is a Node URL object with the `resource` and any query string params already parsed. * The WebSocket request router no longer includes the entire query string when trying to match the path name of the request. * WebSocketRouterRequest objects now include all the properties and events of WebSocketRequest objects. * Removed more console.log statements. Please rely on the various events emitted to be notified of error conditions. I decided that it is not a library's place to spew information to the console. * Renamed the `websocketVersion` property to `webSocketVersion` throughout the code to fix inconsistent capitalization. `websocketVersion` has been kept for compatibility but is deprecated and may be removed in the future. * Now outputting the sanitized version of custom header names rather than the raw value. This prevents invalid HTTP from being put onto the wire if given an illegal header name. I decided it's time to start maintaining a changelog now, starting with version 1.0.1. WebSocket-Node-1.0.34/LICENSE 0000664 0000000 0000000 00000022774 14035643615 0015400 0 ustar 00root root 0000000 0000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS WebSocket-Node-1.0.34/Makefile 0000664 0000000 0000000 00000000224 14035643615 0016015 0 ustar 00root root 0000000 0000000 autobahn: @NODE_PATH=lib node test/autobahn-test-client.js --host=127.0.0.1 --port=9000 autobahn-server: @NODE_PATH=lib node test/echo-server.js WebSocket-Node-1.0.34/README.md 0000664 0000000 0000000 00000021144 14035643615 0015640 0 ustar 00root root 0000000 0000000 WebSocket Client & Server Implementation for Node ================================================= [](http://badge.fury.io/js/websocket) [](https://www.npmjs.com/package/websocket) [ ](https://codeship.com/projects/61106) Overview -------- This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder. Documentation ============= [You can read the full API documentation in the docs folder.](docs/index.md) Changelog --------- ***Current Version: 1.0.34*** - Release 2021-04-14 * Updated browser shim to use the native `globalThis` property when available. See [this MDN page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) for context. Resolves [#415](https://github.com/theturtle32/WebSocket-Node/issues/415) [View the full changelog](CHANGELOG.md) Browser Support --------------- All current browsers are fully supported. * Firefox 7-9 (Old) (Protocol Version 8) * Firefox 10+ (Protocol Version 13) * Chrome 14,15 (Old) (Protocol Version 8) * Chrome 16+ (Protocol Version 13) * Internet Explorer 10+ (Protocol Version 13) * Safari 6+ (Protocol Version 13) Benchmarks ---------- There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4. (These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.) Autobahn Tests -------------- The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability. - [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/) Installation ------------ In your project root: $ npm install websocket Then in your code: ```javascript var WebSocketServer = require('websocket').server; var WebSocketClient = require('websocket').client; var WebSocketFrame = require('websocket').frame; var WebSocketRouter = require('websocket').router; var W3CWebSocket = require('websocket').w3cwebsocket; ``` Current Features: ----------------- - Licensed under the Apache License, Version 2.0 - Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake - Can handle/aggregate received fragmented messages - Can fragment outgoing messages - Router to mount multiple applications to various path and protocol combinations - TLS supported for outbound connections via WebSocketClient - TLS supported for server connections (use https.createServer instead of http.createServer) - Thanks to [pors](https://github.com/pors) for confirming this! - Cookie setting and parsing - Tunable settings - Max Receivable Frame Size - Max Aggregate ReceivedMessage Size - Whether to fragment outgoing messages - Fragmentation chunk size for outgoing messages - Whether to automatically send ping frames for the purposes of keepalive - Keep-alive ping interval - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly) - How long to wait after sending a close frame for acknowledgment before closing the socket. - [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class). Known Issues/Missing Features: ------------------------------ - No API for user-provided protocol extensions. Usage Examples ============== Server Example -------------- Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary. ```javascript #!/usr/bin/env node var WebSocketServer = require('websocket').server; var http = require('http'); var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); response.writeHead(404); response.end(); }); server.listen(8080, function() { console.log((new Date()) + ' Server is listening on port 8080'); }); wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: false }); function originIsAllowed(origin) { // put logic here to detect whether the specified origin is allowed. return true; } wsServer.on('request', function(request) { if (!originIsAllowed(request.origin)) { // Make sure we only accept requests from an allowed origin request.reject(); console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); return; } var connection = request.accept('echo-protocol', request.origin); console.log((new Date()) + ' Connection accepted.'); connection.on('message', function(message) { if (message.type === 'utf8') { console.log('Received Message: ' + message.utf8Data); connection.sendUTF(message.utf8Data); } else if (message.type === 'binary') { console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); connection.sendBytes(message.binaryData); } }); connection.on('close', function(reasonCode, description) { console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); }); }); ``` Client Example -------------- This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number. *This code demonstrates a client in Node.js, not in the browser* ```javascript #!/usr/bin/env node var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { console.log('WebSocket Client Connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('close', function() { console.log('echo-protocol Connection Closed'); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); function sendNumber() { if (connection.connected) { var number = Math.round(Math.random() * 0xFFFFFF); connection.sendUTF(number.toString()); setTimeout(sendNumber, 1000); } } sendNumber(); }); client.connect('ws://localhost:8080/', 'echo-protocol'); ``` Client Example using the *W3C WebSocket API* -------------------------------------------- Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/). ```javascript var W3CWebSocket = require('websocket').w3cwebsocket; var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol'); client.onerror = function() { console.log('Connection Error'); }; client.onopen = function() { console.log('WebSocket Client Connected'); function sendNumber() { if (client.readyState === client.OPEN) { var number = Math.round(Math.random() * 0xFFFFFF); client.send(number.toString()); setTimeout(sendNumber, 1000); } } sendNumber(); }; client.onclose = function() { console.log('echo-protocol Client Closed'); }; client.onmessage = function(e) { if (typeof e.data === 'string') { console.log("Received: '" + e.data + "'"); } }; ``` Request Router Example ---------------------- For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder. Resources --------- A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered) WebSocket-Node-1.0.34/docs/ 0000775 0000000 0000000 00000000000 14035643615 0015307 5 ustar 00root root 0000000 0000000 WebSocket-Node-1.0.34/docs/W3CWebSocket.md 0000664 0000000 0000000 00000003637 14035643615 0020045 0 ustar 00root root 0000000 0000000 W3CWebSocket ============ * [Constructor](#constructor) * [Limitations](#limitations) `var W3CWebSocket = require('websocket').w3cwebsocket` Implementation of the [W3C WebSocket API](http://www.w3.org/TR/websockets/) for browsers. The exposed class lets the developer use the browser *W3C WebSocket API* in Node: ```javascript var WS = require('websocket').w3cwebsocket; WS === window.WebSocket // => true when in the browser var ws = new WS('ws://example.com/resource', 'foo', 'http://example.com'); // - In Node it creates an instance of websocket.W3CWebSocket. // - In the browser it creates an instance of window.WebSocket (third parameter // is ignored by the native WebSocket constructor). ws.onopen = function() { console.log('ws open'); }; // etc. ``` Constructor ----------- ```javascript new W3CWebSocket(requestUrl, requestedProtocols, [[[[origin], headers], requestOptions], clientConfig]) ``` **clientConfig** is the parameter of the [WebSocketClient](./WebSocketClient.md) constructor. **requestUrl**, **requestedProtocols**, **origin**, **headers** and **requestOptions** are parameters to be used in the `connect()` method of [WebSocketClient](./WebSocketClient.md). This constructor API makes it possible to use the W3C API and "browserify" the Node application into a valid browser library. When running in a browser (for example by using [browserify](http://browserify.org/)) the browser's native `WebSocket` implementation is used, and thus just the first and second arguments (`requestUrl` and `requestedProtocols`) are used (those allowed by the *W3C WebSocket API*). Limitations ----------- * `bufferedAmount` attribute is always 0. * `binaryType` is "arraybuffer" by default given that "blob" is not supported (Node does not implement the `Blob` class). * `send()` method allows arguments of type `DOMString`, `ArrayBuffer`, `ArrayBufferView` (`Int8Array`, etc) or Node `Buffer`, but does not allow `Blob`. WebSocket-Node-1.0.34/docs/WebSocketClient.md 0000664 0000000 0000000 00000014222 14035643615 0020657 0 ustar 00root root 0000000 0000000 WebSocketClient =============== * [Constructor](#constructor) * [Config Options](#client-config-options) * [Methods](#methods) * [Events](#events) * **Examples** * [Connect using a Proxy Server](#connect-using-a-proxy-server) `var WebSocketClient = require('websocket').client` This object allows you to make client connections to a WebSocket server. Constructor ----------- ```javascript new WebSocketClient([clientConfig]); ``` Client Config Options --------------------- **webSocketVersion** - uint - *Default: 13* Which version of the WebSocket protocol to use when making the connection. Currently supported values are 8 and 13. This option will be removed once the protocol is finalized by the IETF It is only available to ease the transition through the intermediate draft protocol versions. The only thing this affects the name of the Origin header. **maxReceivedFrameSize** - uint - *Default: 1MiB* The maximum allowed received frame size in bytes. Single frame messages will also be limited to this maximum. **maxReceivedMessageSize** - uint - *Default: 8MiB* The maximum allowed aggregate message size (for fragmented messages) in bytes. **fragmentOutgoingMessages** - Boolean - *Default: true* Whether or not to fragment outgoing messages. If true, messages will be automatically fragmented into chunks of up to `fragmentationThreshold` bytes. **fragmentationThreshold** - uint - *Default: 16KiB* The maximum size of a frame in bytes before it is automatically fragmented. **assembleFragments** - boolean - *Default: true* If true, fragmented messages will be automatically assembled and the full message will be emitted via a `message` event. If false, each frame will be emitted on the WebSocketConnection object via a `frame` event and the application will be responsible for aggregating multiple fragmented frames. Single-frame messages will emit a `message` event in addition to the `frame` event. Most users will want to leave this set to `true`. **closeTimeout** - uint - *Default: 5000* The number of milliseconds to wait after sending a close frame for an acknowledgement to come back before giving up and just closing the socket. **tlsOptions** - object - *Default: {}* Options to pass to `https.request` if connecting via TLS. See [Node's HTTPS documentation](http://nodejs.org/api/https.html#https_https_request_options_callback) Methods ------- ### connect(requestUrl, requestedProtocols, [[[origin], headers], requestOptions]) Will establish a connection to the given `requestUrl`. `requestedProtocols` indicates a list of multiple subprotocols supported by the client. The remote server will select the best subprotocol that it supports and send that back when establishing the connection. `origin` is an optional field that can be used in user-agent scenarios to identify the page containing any scripting content that caused the connection to be requested. (This seems unlikely in node.. probably should leave it null most of the time.) `requestUrl` should be a standard websocket url, such as: `ws://www.mygreatapp.com:1234/websocketapp/` `headers` should be either `null` or an object specifying additional arbitrary HTTP request headers to send along with the request. This may be used to pass things like access tokens, etc. so that the server can verify authentication/authorization before deciding to accept and open the full WebSocket connection. `requestOptions` should be either `null` or an object specifying additional configuration options to be passed to `http.request` or `https.request`. This can be used to pass a custom `agent` to enable `WebSocketClient` usage from behind an HTTP or HTTPS proxy server using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar. `origin` must be specified if you want to pass `headers`, and both `origin` and `headers` must be specified if you want to pass `requestOptions`. The `origin` and `headers` parameters may be passed as `null`. ### abort() Will cancel an in-progress connection request before either the `connect` event or the `connectFailed` event has been emitted. If the `connect` or `connectFailed` event has already been emitted, calling `abort()` will do nothing. Events ------ ### connect `function(webSocketConnection)` Emitted upon successfully negotiating the WebSocket handshake with the remote server. `webSocketConnection` is an instance of `WebSocketConnection` that can be used to send and receive messages with the remote server. ### connectFailed `function(errorDescription)` Emitted when there is an error connecting to the remote host or the handshake response sent by the server is invalid. ### httpResponse `function(response, webSocketClient)` Emitted when the server replies with anything other then "101 Switching Protocols". Provides an opportunity to handle redirects for example. The `response` parameter is an instance of the [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) class. This is not suitable for handling receiving of large response bodies, as the underlying socket will be immediately closed by WebSocket-Node as soon as all handlers for this event are executed. Normally, if the remote server sends an HTTP response with a response code other than 101, the `WebSocketClient` will automatically emit the `connectFailed` event with a description of what was received from the remote server. However, if there are one or more listeners attached to the `httpResponse` event, then the `connectFailed` event will not be emitted for non-101 responses received. `connectFailed` will still be emitted for non-HTTP errors, such as when the remote server is unreachable or not accepting TCP connections. Examples ======== Connect using a Proxy Server ---------------------------- Using [koichik/node-tunnel](https://github.com/koichik/node-tunnel): ```javascript var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); var tunnel = require('tunnel'); var tunnelingAgent = tunnel.httpOverHttp({ proxy: { host: 'proxy.host.com', port: 8080 } }); var requestOptions = { agent: tunnelingAgent }; client.connect('ws://echo.websocket.org/', null, null, null, requestOptions); ``` WebSocket-Node-1.0.34/docs/WebSocketConnection.md 0000664 0000000 0000000 00000017264 14035643615 0021551 0 ustar 00root root 0000000 0000000 WebSocketConnection =================== * [Constructor](#constructor) * [Properties](#properties) * [Methods](#methods) * [Events](#events) This object provides the interface through which you can communicate with connected peers. It is used in both WebSocketServer and WebSocketClient situations. Constructor ----------- This object is created internally by `WebSocketRequest`. Properties ---------- ### closeDescription After the connection is closed, contains a textual description of the reason for the connection closure, or `null` if the connection is still open. ### closeReasonCode After the connection is closed, contains the numeric close reason status code, or `-1` if the connection is still open. ### socket The underlying net.Socket instance for the connection. ### protocol The subprotocol that was chosen to be spoken on this connection. This field will have been converted to lower case. ### extensions An array of extensions that were negotiated for this connection. Currently unused, will always be an empty array. ### remoteAddress The IP address of the remote peer as a string. In the case of a server, the `X-Forwarded-For` header will be respected and preferred for the purposes of populating this field. If you need to get to the actual remote IP address, `webSocketConnection.socket.remoteAddress` will provide it. ### webSocketVersion A number indicating the version of the WebSocket protocol being spoken on this connection. ### connected A boolean value indicating whether or not the connection is still connected. *Read-only* Methods ------- ### close([reasonCode], [description]) Will gracefully close the connection. A close frame will be sent to the remote peer with the provided `reasonCode` and `description` indicating that we wish to close the connection, and we will then wait for up to `config.closeTimeout` milliseconds for an acknowledgment from the remote peer before terminating the underlying socket connection. The `closeTimeout` is passed as part of the `serverOptions` or `clientOptions` hashes to either the `WebSocketServer` or `WebSocketClient` constructors. Most of the time, you should call `close()` without arguments to initiate a normal connection closure. If you specify a `reasonCode` that is defined as one of the standard codes in the WebSocket protocol specification and do not provide a `description`, the default description for the given code will be used. If you would prefer not to send a description at all, pass an empty string `''`as the description parameter. ### drop([reasonCode], [description]) Will send a close frame to the remote peer with the provided `reasonCode` and `description` and will immediately close the socket without waiting for a response. This should generally be used only in error conditions. The default `reasonCode` is 1002 (Protocol Error). Close reasons defined by the WebSocket protocol draft include: ```javascript WebSocketConnection.CLOSE_REASON_NORMAL = 1000; WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001; WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002; WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003; WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning. WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007; WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008; WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009; WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010; ``` ### sendUTF(string) Immediately sends the specified string as a UTF-8 WebSocket message to the remote peer. If `config.fragmentOutgoingMessages` is `true` the message may be sent as multiple fragments if it exceeds `config.fragmentationThreshold` bytes. Any object that implements the `toString()` method may be passed to `sendUTF()` ### sendBytes(buffer) Immediately sends the specified Node `Buffer` object as a Binary WebSocket message to the remote peer. If `config.fragmentOutgoingMessages` is `true` the message may be sent as multiple fragments if it exceeds `config.fragmentationThreshold` bytes. ### send(data) A convenience function that will auto-detect the data type and send the appropriate WebSocket message accordingly. Immediately sends the specified data as either a UTF-8 or Binary message. If `data` is a Node Buffer, a binary message will be sent. Otherwise, the object provided must implement the `toString()` method, and the result of calling `toString()` on the `data` object will be sent as a UTF-8 message. ### ping(data) Sends a ping frame to the remote peer. `data` can be a Node `Buffer` or any object that implements `toString()`, such as a `string` or `number`. Ping frames must not exceed 125 bytes in length. ### pong(buffer) Sends a pong frame to the remote peer. Pong frames may be sent unsolicited and such pong frames will trigger no action on the receiving peer. Pong frames sent in response to a ping frame must mirror the payload data of the ping frame exactly. The `WebSocketConnection` object handles this internally for you, so there should be no need to use this method to respond to pings unless you explicitly cancel() this internal behavior (see ping event below). Pong frames must not exceed 125 bytes in length. ### sendFrame(webSocketFrame) Serializes a `WebSocketFrame` object into binary data and immediately sends it to the remote peer. This is an advanced function, requiring you to manually compose your own `WebSocketFrame`. You should probably use `sendUTF` or `sendBytes` instead. Events ------ ### message `function(message)` Emitted whenever a complete single-frame message is received, or if `config.assembleFragments` is `true` (the default), it will also be emitted with a complete message assembled from multiple fragmented frames. This is the primary event to listen for to receive messages from the remote peer. The `message` object looks like the following: ```javascript // For Text Frames: { type: "utf8", utf8Data: "A string containing the received message." } // For Binary Frames: { type: "binary", binaryData: binaryDataBuffer // a Buffer object containing the binary message payload } ``` ### frame `function(webSocketFrame)` This event is emitted only if `config.assembleFragments` is `false` (default is `true`). This allows you to handle individual fragments as they are received without waiting on `WebSocketConnection` to buffer them into a single `message` event for you. This may be desirable if you are working with streaming data, as it is possible to send fragments continually without ever stopping. `webSocketFrame` is an instance of `WebSocketFrame` which has properties that represent all the individual fields in WebSocket's binary framing protocol. ### close `function(reasonCode, description)` This event is emitted when the connection has been fully closed and the socket is no longer connected. `reasonCode` is the numeric reason code for the connection closure. `description` is a textual explanation for the connection closure, if available. ### error `function(error)` This event is emitted when there has been a socket error. If this occurs, a `close` event will also be emitted. ### ping `function(cancel, data)` This event is emitted when the connection receives a `ping` from the peer. `cancel` is a function taking no arguments that when called prevents the WebSocketConnection object from automatically replying with a `pong`. `data` is the binary payload contained in the ping frame. ### pong `function(data)` This event is emitted when the connection receives a `pong` from the peer. `data` is the binary data contained in the pong frame. WebSocket-Node-1.0.34/docs/WebSocketFrame.md 0000664 0000000 0000000 00000004413 14035643615 0020474 0 ustar 00root root 0000000 0000000 WebSocketFrame ============== * [Constructor](#constructor) * [Properties](#properties) `var WebSocketFrame = require('websocket').frame` This object represents the low level individual frame and is used to drive how the bytes are serialized onto the wire. Constructor ----------- ```javascript new WebSocketFrame(); ``` Properties ---------- ### fin *Boolean* Indicates that this is either the only frame in a message, or the last frame in a fragmentation sequence. ### rsv1 *Boolean* Represents the RSV1 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer. ### rsv2 *Boolean* Represents the RSV2 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer. ### rsv3 *Boolean* Represents the RSV3 field in the framing, which is currently not used. Setting this to true will result in a Protocol Error on the receiving peer. ### mask *uint* Whether or not this frame is (or should be) masked. For outgoing frames, when connected as a client, this flag is automatically forced to `true` by WebSocketConnection. Outgoing frames sent from the server-side of a connection are not masked. ### opcode *uint* Identifies which kind of frame this is. List of Opcodes: Hex - Dec - Description 0x00 - 0 - Continuation 0x01 - 1 - Text Frame 0x02 - 2 - Binary Frame 0x08 - 8 - Close Frame 0x09 - 9 - Ping Frame 0x0A - 10 - Pong Frame ### length *Read-only, uint* Identifies the length of the payload data on a received frame. When sending a frame, the length will be automatically calculated from the `binaryPayload` object. ### binaryPayload *Buffer object* The binary payload data. **NOTE**: Even text frames are sent with a Buffer providing the binary payload data. When sending a UTF-8 Text Frame, you must serialize your string into a Buffer object before constructing your frame, and when receiving a UTF-8 Text Frame, you must deserialize the string from the provided Buffer object. Do not read UTF-8 data from fragmented Text Frames, as it may have fragmented the data in the middle of a UTF-8 encoded character. You should buffer all fragments of a text message before attempting to decode the UTF-8 data. WebSocket-Node-1.0.34/docs/WebSocketRequest.md 0000664 0000000 0000000 00000011424 14035643615 0021072 0 ustar 00root root 0000000 0000000 WebSocketRequest ================ * [Constructor](#constructor) * [Properties](#properties) * [Methods](#methods) * [Events](#events) This object represents a client requesting to connect to the server, and allows you to accept or reject the connection based on whatever criteria you decide. Constructor ----------- This object is created internally by `WebSocketServer`. However if you need to integrate WebSocket support without mounting an instance of `WebSocketServer` to your http server directly, you can handle the `upgrade` event yourself and pass the appropriate parameters to the `WebSocketRequest` constructor. **NOTE:** You *must* pass a complete set of config options to the constructor. See the section *'Server Config Options'* above. The only option that isn't required in this context is `httpServer`. ```javascript new WebSocketRequest(socket, httpRequest, config); ``` The constructor won't immediately parse and validate the handshake from the client, so you need to call `readHandshake()`, which will `throw` an error if the handshake from the client is invalid or if an error is encountered, so it must always be wrapped in a try/catch block. Properties ---------- ### httpRequest A reference to the original Node HTTP request object. This may be useful in combination with some other Node-based web server, such as Express, for accessing cookies or session data. ### host A string containing the contents of the `Host` header passed by the client. This will include the port number if a non-standard port is used. Examples: ``` www.example.com www.example.com:8080 127.0.0.1:3000 ``` ### resource A string containing the path that was requested by the client. ### resourceURL A Node URL object containing the parsed `resource`, including the query string parameters. ### remoteAddress The remote client's IP Address as a string. If an `X-Forwarded-For` header is present, the value will be taken from that header to facilitate WebSocket servers that live behind a reverse-proxy. ### websocketVersion **Deprecated, renamed to webSocketVersion** ### webSocketVersion A number indicating the version of the WebSocket protocol requested by the client. ### origin If the client is a web browser, `origin` will be a string containing the URL of the page containing the script that opened the connection. If the client is **not** a web browser, `origin` may be `null` or "*". ### requestedExtensions An array containing a list of extensions requested by the client. This is not currently used for anything. **Example:** ```javascript [ { name: "simple-extension"; }, { name: "my-great-compression-extension", params: [ { name: "compressionLevel", value: "10"; } ] } ] ``` ### requestedProtocols An array containing a list of strings that indicate the subprotocols the client would like to speak. The server should select the best one that it can support from the list and pass it to the accept() function when accepting the connection. Note that all the strings in the `requestedProtocols` array will have been converted to lower case, so that acceptance of a subprotocol can be case-insensitive. Methods ------- ### accept(acceptedProtocol, allowedOrigin) *Returns: WebSocketConnection instance* After inspecting the WebSocketRequest's properties, call this function on the request object to accept the connection. If you don't have a particular subprotocol you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. Note that the `acceptedProtocol` parameter is *case-insensitive*, and you must either pass a value that was originally requested by the client or `null`. For browser clients (in which the `origin` property would be non-null) you must pass that user's origin as the `allowedOrigin` parameter to confirm that you wish to accept connections from the given origin. The return value contains the established `WebSocketConnection` instance that can be used to communicate with the connected client. ### reject([httpStatus], [reason]) If you decide to reject the connection, you must call `reject`. You may optionally pass in an HTTP Status code (such as 404) and a textual description that will be sent to the client in the form of an "X-WebSocket-Reject-Reason" header. The connection will then be closed. Events ------ ### requestAccepted `function(webSocketConnection)` Emitted by the WebSocketRequest object when the `accept` method has been called and the connection has been established. `webSocketConnection` is the established `WebSocketConnection` instance that can be used to communicate with the connected client. ### requestRejected `function()` Emitted by the WebSocketRequest object when the `reject` method has been called and the connection has been terminated. WebSocket-Node-1.0.34/docs/WebSocketServer.md 0000664 0000000 0000000 00000015326 14035643615 0020715 0 ustar 00root root 0000000 0000000 WebSocketServer =============== * [Constructor](#constructor) * [Config Options](#server-config-options) * [Properties](#properties) * [Methods](#methods) * [Events](#events) `var WebSocketServer = require('websocket').server` Constructor ----------- ```javascript new WebSocketServer([serverConfig]); ``` Methods ------- ### mount(serverConfig) `mount` will attach the WebSocketServer instance to a Node http.Server instance. `serverConfig` is required, and is an object with configuration values. For those values, see **Server Config Options** below. If you passed `serverConfig` to the constructor, this function will automatically be invoked. ### unmount() `unmount` will detach the WebSocketServer instance from the Node http.Server instance. All existing connections are left alone and will not be affected, but no new WebSocket connections will be accepted. ### closeAllConnections() Will gracefully close all open WebSocket connections. ### shutDown() Gracefully closes all open WebSocket connections and unmounts the server from the Node http.Server instance. Server Config Options --------------------- **httpServer** - (http.Server instance) **Required**. The Node http or https server instance(s) to attach to. You can pass a single instance directly, or pass an array of instances to attach to multiple http/https servers. Passing an array is particularly useful when you want to accept encrypted and unencrypted WebSocket connections on both ws:// and wss:// protocols using the same WebSocketServer instance. **maxReceivedFrameSize** - uint - *Default: 64KiB* The maximum allowed received frame size in bytes. Single frame messages will also be limited to this maximum. **maxReceivedMessageSize** - uint - *Default: 1MiB* The maximum allowed aggregate message size (for fragmented messages) in bytes. **fragmentOutgoingMessages** - Boolean - *Default: true* Whether or not to fragment outgoing messages. If true, messages will be automatically fragmented into chunks of up to `fragmentationThreshold` bytes. **fragmentationThreshold** - uint - *Default: 16KiB* The maximum size of a frame in bytes before it is automatically fragmented. **keepalive** - boolean - *Default: true* If true, the server will automatically send a ping to all clients every `keepaliveInterval` milliseconds. Each client has an independent keepalive timer, which is reset when any data is received from that client. **keepaliveInterval** - uint - *Default: 20000* The interval in milliseconds to send keepalive pings to connected clients. **dropConnectionOnKeepaliveTimeout** - boolean - *Default: true* If true, the server will consider any connection that has not received any data within the amount of time specified by `keepaliveGracePeriod` after a keepalive ping has been sent. Ignored if `keepalive` is false. **keepaliveGracePeriod** - uint - *Default: 10000* The amount of time to wait after sending a keepalive ping before closing the connection if the connected peer does not respond. Ignored if `keepalive` or `dropConnectionOnKeepaliveTimeout` are false. The grace period timer is reset when any data is received from the client. **assembleFragments** - boolean - *Default: true* If true, fragmented messages will be automatically assembled and the full message will be emitted via a `message` event. If false, each frame will be emitted on the WebSocketConnection object via a `frame` event and the application will be responsible for aggregating multiple fragmented frames. Single-frame messages will emit a `message` event in addition to the `frame` event. Most users will want to leave this set to `true`. **autoAcceptConnections** - boolean - *Default: false* If this is true, websocket connections will be accepted regardless of the path and protocol specified by the client. The protocol accepted will be the first that was requested by the client. Clients from any origin will be accepted. This should only be used in the simplest of cases. You should probably leave this set to `false`; and inspect the request object to make sure it's acceptable before accepting it. **closeTimeout** - uint - *Default: 5000* The number of milliseconds to wait after sending a close frame for an acknowledgement to come back before giving up and just closing the socket. **disableNagleAlgorithm** - boolean - *Default: true* The Nagle Algorithm makes more efficient use of network resources by introducing a small delay before sending small packets so that multiple messages can be batched together before going onto the wire. This however comes at the cost of latency, so the default is to disable it. If you don't need low latency and are streaming lots of small messages, you can change this to 'false'; **ignoreXForwardedFor** - Boolean - *Default: false* Whether or not the `X-Forwarded-For` header should be respected. It's important to set this to 'true' when accepting connections from untrusted clients, as a malicious client could spoof its IP address by simply setting this header. It's meant to be added by a trusted proxy or other intermediary within your own infrastructure. More info: [X-Forwarded-For on Wikipedia](http://en.wikipedia.org/wiki/X-Forwarded-For) **parseExtensions** - Boolean - *Default: true* Whether or not to parse 'sec-websocket-extension' headers. Array is exposed to WebSocketRequest.requestedExtensions. **parseCookies** - Boolean - *Default: true* Whether or not to parse 'cookie' headers. Array is exposed to WebSocketRequest.cookies. Events ------ There are three events emitted by a WebSocketServer instance that allow you to handle incoming requests, establish connections, and detect when a connection has been closed. ### request `function(webSocketRequest)` If `autoAcceptConnections` is set to `false`, a `request` event will be emitted by the server whenever a new WebSocket request is made. You should inspect the requested protocols and the user's origin to verify the connection, and then accept or reject it by calling webSocketRequest.accept('chosen-protocol', 'accepted-origin') or webSocketRequest.reject() ### connect `function(webSocketConnection)` Emitted whenever a new WebSocket connection is accepted. ### close `function(webSocketConnection, closeReason, description)` Whenever a connection is closed for any reason, the WebSocketServer instance will emit a `close` event, passing a reference to the WebSocketConnection instance that was closed. `closeReason` is the numeric reason status code for the connection closure, and `description` is a textual description of the close reason, if available. ### upgradeError `function(error)` Emitted whenever a WebSocket error happens during the connection upgrade phase. Note that the WS connection is automatically rejected with a 400 error code, this event just exposes the error. WebSocket-Node-1.0.34/docs/index.md 0000664 0000000 0000000 00000001206 14035643615 0016737 0 ustar 00root root 0000000 0000000 WebSocket-Node Documentation ============================ WebSocket-Node includes both client and server functionality, available through WebSocketClient and WebSocketServer respectively. Once a connection is established, the API for sending and receiving messages is identical whether you're acting as a client or server. Click on one of the classes below to view its API documentation. * [WebSocketClient](./WebSocketClient.md) * [WebSocketConnection](./WebSocketConnection.md) * [WebSocketFrame](./WebSocketFrame.md) * [WebSocketRequest](./WebSocketRequest.md) * [WebSocketServer](./WebSocketServer.md) * [W3CWebSocket](./W3CWebSocket.md) WebSocket-Node-1.0.34/example/ 0000775 0000000 0000000 00000000000 14035643615 0016012 5 ustar 00root root 0000000 0000000 WebSocket-Node-1.0.34/example/whiteboard/ 0000775 0000000 0000000 00000000000 14035643615 0020142 5 ustar 00root root 0000000 0000000 WebSocket-Node-1.0.34/example/whiteboard/README 0000664 0000000 0000000 00000000456 14035643615 0021027 0 ustar 00root root 0000000 0000000 To run the whiteboard example, make sure to run.. npm install "express@2.3.11" "ejs@0.4.3" ..from within the 'whiteboard' folder, then fire up the example server with.. node ./whiteboard.js ..and navigate to http://localhost:8080 from a browser supporting draft-09 of the WebSockets specification. WebSocket-Node-1.0.34/example/whiteboard/index.ejs 0000664 0000000 0000000 00000003620 14035643615 0021755 0 ustar 00root root 0000000 0000000
As of the time of this writing, this example requires at least Firefox 7 beta or Chrome 14 beta.