Compare commits

...

37 Commits
2.0.1 ... 2.1.1

Author SHA1 Message Date
Damien Arrachequesne
e0b2cb0c5a [chore] Release 2.1.1 2018-05-17 23:22:49 +02:00
Sleiman Sleiman
1decae341c [feat] Add local flag to the socket object (#3219)
To match the behaviour on the namespace (see #2628).
2018-04-27 13:03:25 +02:00
Donut
0279c47c8c [docs] Convert the chat example to ES6 (#3227) 2018-04-27 13:00:27 +02:00
Damien Arrachequesne
2917942b3e [docs] Clarify private messaging in the emit cheatsheet (#3232)
The previous version was confusing, as `socket.to(socket.id).emit()` does nothing.

Fixes #3220
2018-04-27 12:50:31 +02:00
Damien Arrachequesne
db831a3de4 [chore] Release 2.1.0 2018-03-29 23:30:03 +02:00
Damien Arrachequesne
ac945d1eba [feat] Add support for dynamic namespaces (#3195)
This follows #3187, with a slightly different API.

A dynamic namespace can be created with:

```js
io.of(/^\/dynamic-\d+$/).on('connect', (socket) => { /* ... */ });
```
2018-03-29 23:08:08 +02:00
Scott Gress
ad0c052eff [docs] Add note in docs for origins(fn) about error needing to be a string. (#2895) 2018-03-10 09:03:28 +01:00
Damien Arrachequesne
1f1d64bab6 [fix] Include the protocol in the origins check (#3198)
Previously, the protocol was not taken in account, which caused the following behaviour:

```js
io.origins('https://foo.example.com:443'); // ok as a string
io.origins(['https://foo.example.com:443'); // not ok as an array
```

Fixes #3190
2018-03-10 08:56:42 +01:00
Damien Arrachequesne
f4fc517e0f [fix] Properly emit 'connect' when using a custom namespace (#3197)
When using a custom namespace with a middleware, the client did not receive the 'connect' event.

Fixes #3082
2018-03-10 08:51:22 +01:00
Jumper Chen
be61ba0a20 [docs] Add link to a Dart client implementation (#2940) 2018-03-01 00:23:45 +01:00
Damien Arrachequesne
c0c79f019e [feat] Add support for dynamic namespaces (#3187) 2018-03-01 00:22:16 +01:00
Damien Arrachequesne
dea5214f21 [chore] Bump superagent and supertest versions (#3186) 2018-02-28 23:19:19 +01:00
Damien Arrachequesne
b1941d5dfe [chore] Bump engine.io to version 3.2.0 2018-02-28 23:10:40 +01:00
Miguel Piedrafita
a23007a635 [docs] Update license year (#3153) 2018-02-28 23:03:02 +01:00
Damien Arrachequesne
f48a06c040 [feat] Add a 'binary' flag (#3185)
So that the call to the `has-binary` method can be skipped. Usage:

```
// with binary data
socket.binary(true).emit("binary", obj);

// without binary data
socket.binary(false).emit("string", obj);

// call to hasBin
socket.emit("guess", obj);
```
2018-02-28 23:00:16 +01:00
Damien Arrachequesne
0539a2c4fd [test] Update travis configuration 2018-02-28 22:56:28 +01:00
Devlin Pajaron
c06ac071d0 [docs] Fix typo (#3157) 2018-02-25 09:26:24 +01:00
Damien Arrachequesne
52b09609db [chore] Bump debug to version 3.1.0 2018-02-25 09:22:40 +01:00
Damien Arrachequesne
1c108a35e4 [chore] Release 2.0.4 2017-10-22 15:16:29 +02:00
Thiago Santos
f333479080 [test] Use npm scripts instead of gulp (#3078) 2017-10-16 07:46:42 +02:00
Carson McKinstry
3f611654f2 [docs] Fix a grammar mistake in the API docs (#3076) 2017-10-07 15:08:14 +02:00
Vyacheslav Aristov
e26b71c78e [docs] Fix typo in API docs (#3066) 2017-10-07 14:36:02 +02:00
Haku
3386e155a8 [docs] Actually prevent input from having injected markup in chat example (#2987) 2017-08-27 08:40:26 +02:00
Stanley288
3684d590f5 [docs] Use path.join instead of concatenating paths (#3014) 2017-08-26 07:44:25 +02:00
Damien Arrachequesne
dd69abbeee [fix] Reset rooms object before broadcasting from namespace (#3039) 2017-08-26 07:36:26 +02:00
Damien Arrachequesne
1f0e64a6da [fix] Do not throw when receiving an unhandled error packet (#3038) 2017-08-26 07:35:57 +02:00
Gabriel Hautclocq
9d170a75d0 [docs] Add io.emit in the cheat sheet (#2992) 2017-07-01 07:57:34 +02:00
Nicolas Coden
7199d1b6ef [docs] Fix misnamed 'Object.keys' in API docs (#2979) 2017-06-19 12:16:26 +02:00
Damien Arrachequesne
bf7afb14cb [docs] Update Webpack server example (#2976) 2017-06-15 23:40:43 +02:00
Damien Arrachequesne
410f5bcb8e [docs] Update API documentation (#2973) 2017-06-13 23:05:26 +02:00
Damien Arrachequesne
65ece01135 [chore] Release 2.0.3 2017-06-12 14:05:46 +02:00
Damien Arrachequesne
db0c69969e [fix] Reset rooms object before broadcasting (#2970)
It seems packets could be delivered to wrong room in some case, if the
_rooms array was not reset before the next emit.
2017-06-12 14:01:35 +02:00
Damien Arrachequesne
94df7bcdfd [fix] Fix middleware initialization (#2969)
Fix "TypeError: Cannot convert undefined or null to object" when a
middleware is added before the engine is properly attached.
2017-06-12 14:00:48 +02:00
Ra'Shaun Stovall
9a014e2df4 [docs] Update slack badge (#2961)
Update badge to https://slackin-socketio.now.sh/badge.svg
2017-06-08 12:28:56 +02:00
Damien Arrachequesne
2b10f1b3a4 [docs] Update webpack example (#2960) 2017-06-03 13:53:03 +02:00
Damien Arrachequesne
a10dc8d92d [chore] Release 2.0.2 2017-06-01 14:01:24 +02:00
Damien Arrachequesne
2b216902e1 [fix] Fix timing issues with middleware (#2948)
Using a middleware could previously lead to a connecting client
receiving a connect event from the server before the server triggers
its own connect event.
2017-05-22 13:01:59 +02:00
26 changed files with 825 additions and 1045 deletions

1
.gitignore vendored
View File

@@ -11,3 +11,4 @@ node_modules
coverage
.idea
dist
.nyc_output

View File

@@ -1,12 +1,14 @@
sudo: false
language: node_js
sudo: false
node_js:
- "4"
- "6"
- "7"
git:
depth: 1
- '4'
- '6'
- '8'
- node
notifications:
irc: "irc.freenode.org#socket.io"
git:
depth: 1
cache:
directories:
- node_modules

View File

@@ -1,707 +0,0 @@
2.0.1 / 2017-05-09
===================
* [fix] Update path of client file (#2934)
2.0.0 / 2017-05-09
===================
* [feat] Move binary detection to the parser (#2923)
* [feat] Allow to join several rooms at once (#2879)
* [feat] Merge Engine.IO and Socket.IO handshake packets (#2833)
* [feat] Allow the use of custom parsers (#2829)
* [fix] Use path.resolve by default and require.resolve as a fallback (#2797)
* [fix] Properly close the connection on error (#2681)
* [fix] Prevent null from being accepted as argument (#2606)
* [perf] Use shared instance of the encoder (#2825)
* [perf] Reset properties instead of deleting them (#2826)
* [perf] micro-optimisations (#2793)
* [chore] Merge history of 1.7.x and 0.9.x branches (#2930)
* [chore] Added backers and sponsors on the README (#2933)
* [chore] Bump dependencies (#2926)
* [chore] Bump socket.io-adapter to version 1.0.0 (#2867)
* [chore] Bump engine.io to version 2.0.2 (#2864)
* [chore] Bump engine.io to version 2.0.0 (#2832)
* [chore] Update issue template with fiddle (#2811)
* [chore] Update copyright year LICENSE to 2017 (#2803)
* [docs] Add an example of custom parser (#2929)
* [docs] Replace non-breaking space with proper whitespace (#2913)
* [docs] Update emit cheatsheet (#2906)
* [docs] Explicitly document that Server extends EventEmitter (#2874)
* [docs] Add server.engine.generateId attribute (#2880)
* [docs] Fix wrong space character in README (#2900)
* [docs] Fix documentation for 'connect' event (#2898)
* [docs] Add webpack build example (#2828)
* [docs] Update the wording to match the code example (#2853)
* [docs] Small addition to the Express Readme Part (#2846)
* [docs] Add a 'Features' section in the README (#2824)
* [docs] Add httpd cluster example (#2819)
* [docs] Add haproxy cluster example (#2818)
* [docs] Add nginx cluster example (#2817)
* [docs] Implement whiteboard example (#2810)
* [docs] Fix documentation for `local` flag (#2816)
* [docs] Add emit cheatsheet (#2815)
* [docs] Add pingInterval/pingTimeout/transports options in the API documentation (#2814)
* [docs] Add an example for socket.join() method (#2813)
* [docs] Fix a typo on `clients` method in the API documentation (#2812)
* [docs] Fix wrong argument name in API.md (#2802)
* [docs] Add install script on Readme.md (#2780)
* [docs] API documentation (#2784)
1.7.4 / 2017-05-07
===================
* [chore] Bump engine.io to version 1.8.4
0.9.18 / 2017-05-07
===================
* Remove process.EventEmitter usage for Node 7.x
1.7.3 / 2017-02-17
===================
* [chore] Bump engine.io to version 1.8.3
1.7.2 / 2016-12-11
===================
* [chore] Bump engine.io to version 1.8.2 (#2782)
* [fix] Fixes socket.use error packet (#2772)
1.7.1 / 2016-11-28
===================
1.7.0 / 2016-11-27
===================
* [docs] Comment connected socket availability for adapters (#2081)
* [docs] Fixed grammar issues in the README.md (#2159)
* [feature] serve sourcemap for socket.io-client (#2482)
* [feature] Add a `local` flag (#2628)
* [chore] Bump engine.io to version 1.8.1 (#2765)
* [chore] Update client location and serve minified file (#2766)
1.6.0 / 2016-11-20
==================
* [fix] Make ETag header comply with standard. (#2603)
* [feature] Loading client script on demand. (#2567)
* [test] Fix leaking clientSocket (#2721)
* [feature] Add support for all event emitter methods (#2601)
* [chore] Update year to 2016 (#2456)
* [feature] Add support for socket middleware (#2306)
* [feature] add support for Server#close(callback) (#2748)
* [fix] Don't drop query variables on handshake (#2745)
* [example] Add disconnection/reconnection logs to the chat example (#2675)
* [perf] Minor code optimizations (#2219)
* [chore] Bump debug to version 2.3.3 (#2754)
* [chore] Bump engine.io to version 1.8.0 (#2755)
* [chore] Bump socket.io-adapter to version 0.5.0 (#2756)
1.5.1 / 2016-10-24
==================
* [fix] Avoid swallowing exceptions thrown by user event handlers (#2682)
* [test] Use client function to unify `client` in test script (#2731)
* [docs] Add link to LICENSE (#2221)
* [docs] Fix JSDoc of optional parameters (#2465)
* [docs] Fix typo (#2724)
* [docs] Link readme npm package badge to npm registry page (#2612)
* [docs] Minor fixes (#2526)
* [chore] Bump socket.io-parser to 2.3.0 (#2730)
* [chore] Add Github issue and PR templates (#2733)
* [chore] Bump engine.io to 1.7.2 (#2729)
* [chore] Bump socket.io-parser to 2.3.1 (#2734)
1.5.0 / 2016-10-06
==================
* [feature] stop append /# before id when no namespace (#2508)
* [feature] Add a 'disconnecting' event to access to socket.rooms upon disconnection (#2332)
* [fix] Fix query string management (#2422)
* [fix] add quote to exec paths, prevent error when spaces in path (#2508)
* [docs] Prevent mixup for new programmers (#2599)
* [example] Fix chat display in Firefox (#2477)
* [chore] Add gulp & babel in the build process (#2471)
* [chore] Bump engine.io to 1.7.0 (#2707)
* [chore] Remove unused zuul-ngrok dependency (#2708)
* [chore] Point towards current master of socket.io-client (#2710)
* [chore] Restrict files included in npm package (#2709)
* [chore] Link build badge to master branch (#2549)
1.4.8 / 2016-06-23
==================
* package: bump `engine.io`
1.4.7 / 2016-06-23
==================
* package: bump `engine.io`
1.4.6 / 2016-05-02
==================
* package: bump engine.io
1.4.5 / 2016-01-26
==================
* fix closing the underlying `http.Server`
1.4.4 / 2016-01-10
==================
* package: bump `engine.io`
1.4.3 / 2016-01-08
==================
* bump `socket.io-client`
1.4.2 / 2016-01-07
==================
* bump `engine.io`
1.4.1 / 2016-01-07
==================
* version bump
1.4.0 / 2015-11-28
==================
* socket.io: increase large binary data test timeout
* package: bump `engine.io` for release
* trigger callback even when joining an already joined room
* package: bump parser
* namespace: clear rooms flag after a clients call (fixes #1978)
* package: bump `socket.io-parser`
* fixed tests with large data
* fixed a typo in the example code
* package: bump mocha
* package: bump `has-binary` and `zuul-ngrok`
* package: bump `engine.io` and `socket.io-client`
* README: clarified documentation of Socket.in
* README: fixed up legacy repo links
* test: better timeout for stress test
* socket: don't set request property which has a getter
* removed proxy index file
* support flags on namespace
* improve Socket#packet and Client#packet
* socket: warn node_redis-style about missing `error`
* test: added failing test
* test: increase timeout for large binary data test
* package: bump `has-binary` to work with all objects (fixes #1955)
* fix origin verification default https port [evanlucas]
* support compression [nkzawa]
* changed type of `Client#sockets`, `Namespace#sockets` and `Socket#rooms` to maps (instead of arrays)
1.3.7 / 2015-09-21
==================
* package: bump `socket.io-client` for node4 compatibility
* package: bump `engine.io` for node4 compatibility
1.3.6 / 2015-07-14
==================
* package: bump `engine.io` to fix build on windows
1.3.5 / 2015-03-03
==================
* package: bump `socket.io-parser`
1.3.4 / 2015-02-14
==================
* package: bump `socket.io-client`
1.3.3 / 2015-02-03
==================
* socket: warn node_redis-style about missing `error`
* package: bump parser to better handle bad binary packets
1.3.2 / 2015-01-19
==================
* no change on this release
1.3.1 / 2015-01-19
==================
* no change on this release
* package: bump `engine.io`
1.3.0 / 2015-01-19
==================
* package: bump `engine.io`
* add test for reconnection after server restarts [rase-]
* update license with up-to-date year range [fay-jai]
* fix leaving unknown rooms [defunctzombie]
* allow null origins when allowed origins is a function [drewblaisdell]
* fix tests on node 0.11
* package: fix `npm test` to run on windows
* package: bump `debug` v2.1.0 [coderaiser]
* added tests for volatile [rase-]
1.2.1 / 2014-11-21
==================
* fix protocol violations and improve error handling (GH-1880)
* package: bump `engine.io` for websocket leak fix [3rd-Eden]
* style tweaks
1.2.0 / 2014-10-27
==================
* package: bump `engine.io`
* downloads badge
* add test to check that empty rooms are autopruned
* added Server#origins(v:Function) description for dynamic CORS
* added test coverage for Server#origins(function) for dynamic CORS
* added optional Server#origins(function) for dynamic CORS
* fix usage example for Server#close
* package: fix main file for example application 'chat'
* package: bump `socket.io-parser`
* update README http ctor to createServer()
* bump adapter with a lot of fixes for room bookkeeping
1.1.0 / 2014-09-04
==================
* examples: minor fix of escaping
* testing for equivalence of namespaces starting with / or without
* update index.js
* added relevant tests
* take "" and "/" as equivalent namespaces on server
* use svg instead of png to get better image quality in readme
* make CI build faster
* fix splice arguments and `socket.rooms` value update in `socket.leaveAll`.
* client cannot connect to non-existing namespaces
* bump engine.io version to get the cached IP address
* fixed handshake object address property and made the test case more strict.
* package: bump `engine.io`
* fixed the failing test where server crashes on disconnect involving connectBuffer
* npmignore: ignore `.gitignore` (fixes #1607)
* test: added failing case for `socket.disconnect` and nsps
* fix repo in package.json
* improve Close documentation
* use ephemeral ports
* fix: We should use the standard http protocol to handler the etag header.
* override default browser font-family for inputs
* update has-binary-data to 1.0.3
* add close specs
* add ability to stop the http server even if not created inside socket.io
* make sure server gets close
* Add test case for checking that reconnect_failed is fired only once upon failure
* package: bump `socket.io-parser` for `component-emitter` dep fix
1.0.6 / 2014-06-19
==================
* package: bump `socket.io-client`
1.0.5 / 2014-06-16
==================
* package: bump `engine.io` to fix jsonp `\n` bug and CORS warnings
* index: fix typo [yanatan16]
* add `removeListener` to blacklisted events
* examples: clearer instructions to install chat example
* index: fix namespace `connectBuffer` issue
1.0.4 / 2014-06-02
==================
* package: bump socket.io-client
1.0.3 / 2014-05-31
==================
* package: bump `socket.io-client`
* package: bump `socket.io-parser` for binary ACK fix
* package: bump `engine.io` for binary UTF8 fix
* example: fix XSS in chat example
1.0.2 / 2014-05-28
==================
* package: bump `socket.io-parser` for windows fix
1.0.1 / 2014-05-28
==================
* bump due to bad npm tag
1.0.0 / 2014-05-28
==================
* stable release
1.0.0-pre5 / 2014-05-22
=======================
* package: bump `socket.io-client` for parser fixes
* package: bump `engine.io`
1.0.0-pre4 / 2014-05-19
=======================
* package: bump client
1.0.0-pre3 / 2014-05-17
=======================
* package: bump parser
* package: bump engine.io
1.0.0-pre2 / 2014-04-27
=======================
* package: bump `engine.io`
* added backwards compatible of engine.io maxHttpBufferSize
* added test that server and client using same protocol
* added support for setting allowed origins
* added information about logging
* the set function in server can be used to set some attributes for BC
* fix error in callback call 'done' instead of 'next' in docs
* package: bump `socket.io-parser`
* package: bump `expect.js`
* added some new tests, including binary with acks
1.0.0-pre / 2014-03-14
======================
* implemented `engine.io`
* implemented `socket.io-adapter`
* implemented `socket.io-protocol`
* implemented `debug` and improved instrumentation
* added binary support
* added new `require('io')(srv)` signature
* simplified `socket.io-client` serving
0.9.14 / 2013-03-29
===================
* manager: fix memory leak with SSL [jpallen]
0.9.13 / 2012-12-13
===================
* package: fixed `base64id` requirement
0.9.12 / 2012-12-13
===================
* manager: fix for latest node which is returning a clone with `listeners` [viirya]
0.9.11 / 2012-11-02
===================
* package: move redis to optionalDependenices [3rd-Eden]
* bumped client
0.9.10 / 2012-08-10
===================
* Don't lowercase log messages
* Always set the HTTP response in case an error should be returned to the client
* Create or destroy the flash policy server on configuration change
* Honour configuration to disable flash policy server
* Add express 3.0 instructions on Readme.md
* Bump client
0.9.9 / 2012-08-01
==================
* Fixed sync disconnect xhrs handling
* Put license text in its own file (#965)
* Add warning to .listen() to ease the migration to Express 3.x
* Restored compatibility with node 0.4.x
0.9.8 / 2012-07-24
==================
* Bumped client.
0.9.7 / 2012-07-24
==================
* Prevent crash when socket leaves a room twice.
* Corrects unsafe usage of for..in
* Fix for node 0.8 with `gzip compression` [vadimi]
* Update redis to support Node 0.8.x
* Made ID generation securely random
* Fix Redis Store race condition in manager onOpen unsubscribe callback
* Fix for EventEmitters always reusing the same Array instance for listeners
0.9.6 / 2012-04-17
==================
* Fixed XSS in jsonp-polling.
0.9.5 / 2012-04-05
==================
* Added test for polling and socket close.
* Ensure close upon request close.
* Fix disconnection reason being lost for polling transports.
* Ensure that polling transports work with Connection: close.
* Log disconnection reason.
0.9.4 / 2012-04-01
==================
* Disconnecting from namespace improvement (#795) [DanielBaulig]
* Bumped client with polling reconnection loop (#438)
0.9.3 / 2012-03-28
==================
* Fix "Syntax error" on FF Web Console with XHR Polling [mikito]
0.9.2 / 2012-03-13
==================
* More sensible close `timeout default` (fixes disconnect issue)
0.9.1-1 / 2012-03-02
====================
* Bumped client with NPM dependency fix.
0.9.1 / 2012-03-02
==================
* Changed heartbeat timeout and interval defaults (60 and 25 seconds)
* Make tests work both on 0.4 and 0.6
* Updated client (improvements + bug fixes).
0.9.0 / 2012-02-26
==================
* Make it possible to use a regexp to match the socket.io resource URL.
We need this because we have to prefix the socket.io URL with a variable ID.
* Supplemental fix to gavinuhma/authfix, it looks like the same Access-Control-Origin logic is needed in the http and xhr-polling transports
* Updated express dep for windows compatibility.
* Combine two substr calls into one in decodePayload to improve performance
* Minor documentation fix
* Minor. Conform to style of other files.
* Switching setting to 'match origin protocol'
* Revert "Fixes leaking Redis subscriptions for #663. The local flag was not getting passed through onClientDisconnect()."
* Revert "Handle leaked dispatch:[id] subscription."
* Merge pull request #667 from dshaw/patch/redis-disconnect
* Handle leaked dispatch:[id] subscription.
* Fixes leaking Redis subscriptions for #663. The local flag was not getting passed through onClientDisconnect().
* Prevent memory leaking on uncompleted requests & add max post size limitation
* Fix for testcase
* Set Access-Control-Allow-Credentials true, regardless of cookie
* Remove assertvarnish from package as it breaks on 0.6
* Correct irc channel
* Added proper return after reserved field error
* Fixes manager.js failure to close connection after transport error has happened
* Added implicit port 80 for origin checks. fixes #638
* Fixed bug #432 in 0.8.7
* Set Access-Control-Allow-Origin header to origin to enable withCredentials
* Adding configuration variable matchOriginProtocol
* Fixes location mismatch error in Safari.
* Use tty to detect if we should add colors or not by default.
* Updated the package location.
0.8.7 / 2011-11-05
==================
* Fixed memory leaks in closed clients.
* Fixed memory leaks in namespaces.
* Fixed websocket handling for malformed requests from proxies. [einaros]
* Node 0.6 compatibility. [einaros] [3rd-Eden]
* Adapted tests and examples.
0.8.6 / 2011-10-27
==================
* Added JSON decoding on jsonp-polling transport.
* Fixed README example.
* Major speed optimizations [3rd-Eden] [einaros] [visionmedia]
* Added decode/encode benchmarks [visionmedia]
* Added support for black-listing client sent events.
* Fixed logging options, closes #540 [3rd-Eden]
* Added vary header for gzip [3rd-Eden]
* Properly cleaned up async websocket / flashsocket tests, after patching node-websocket-client
* Patched to properly shut down when a finishClose call is made during connection establishment
* Added support for socket.io version on url and far-future Expires [3rd-Eden] [getify]
* Began IE10 compatibility [einaros] [tbranyen]
* Misc WebSocket fixes [einaros]
* Added UTF8 to respone headers for htmlfile [3rd-Eden]
0.8.5 / 2011-10-07
==================
* Added websocket draft HyBi-16 support. [einaros]
* Fixed websocket continuation bugs. [einaros]
* Fixed flashsocket transport name.
* Fixed websocket tests.
* Ensured `parser#decodePayload` doesn't choke.
* Added http referrer verification to manager verifyOrigin.
* Added access control for cross domain xhr handshakes [3rd-Eden]
* Added support for automatic generation of socket.io files [3rd-Eden]
* Added websocket binary support [einaros]
* Added gzip support for socket.io.js [3rd-Eden]
* Expose socket.transport [3rd-Eden]
* Updated client.
0.8.4 / 2011-09-06
==================
* Client build
0.8.3 / 2011-09-03
==================
* Fixed `\n` parsing for non-JSON packets (fixes #479).
* Fixed parsing of certain unicode characters (fixes #451).
* Fixed transport message packet logging.
* Fixed emission of `error` event resulting in an uncaught exception if unhandled (fixes #476).
* Fixed; allow for falsy values as the configuration value of `log level` (fixes #491).
* Fixed repository URI in `package.json`. Fixes #504.
* Added text/plain content-type to handshake responses [einaros]
* Improved single byte writes [einaros]
* Updated socket.io-flashsocket default port from 843 to 10843 [3rd-Eden]
* Updated client.
0.8.2 / 2011-08-29
==================
* Updated client.
0.8.1 / 2011-08-29
==================
* Fixed utf8 bug in send framing in websocket [einaros]
* Fixed typo in docs [Znarkus]
* Fixed bug in send framing for over 64kB of data in websocket [einaros]
* Corrected ping handling in websocket transport [einaros]
0.8.0 / 2011-08-28
==================
* Updated to work with two-level websocket versioning. [einaros]
* Added hybi07 support. [einaros]
* Added hybi10 support. [einaros]
* Added http referrer verification to manager.js verifyOrigin. [einaors]
0.7.11 / 2011-08-27
===================
* Updated socket.io-client.
0.7.10 / 2011-08-27
===================
* Updated socket.io-client.
0.7.9 / 2011-08-12
==================
* Updated socket.io-client.
* Make sure we only do garbage collection when the server we receive is actually run.
0.7.8 / 2011-08-08
==================
* Changed; make sure sio#listen passes options to both HTTP server and socket.io manager.
* Added docs for sio#listen.
* Added options parameter support for Manager constructor.
* Added memory leaks tests and test-leaks Makefile task.
* Removed auto npm-linking from make test.
* Make sure that you can disable heartbeats. [3rd-Eden]
* Fixed rooms memory leak [3rd-Eden]
* Send response once we got all POST data, not immediately [Pita]
* Fixed onLeave behavior with missing clientsk [3rd-Eden]
* Prevent duplicate references in rooms.
* Added alias for `to` to `in` and `in` to `to`.
* Fixed roomClients definition.
* Removed dependency on redis for installation without npm [3rd-Eden]
* Expose path and querystring in handshakeData [3rd-Eden]
0.7.7 / 2011-07-12
==================
* Fixed double dispatch handling with emit to closed clients.
* Added test for emitting to closed clients to prevent regression.
* Fixed race condition in redis test.
* Changed Transport#end instrumentation.
* Leveraged $emit instead of emit internally.
* Made tests faster.
* Fixed double disconnect events.
* Fixed disconnect logic
* Simplified remote events handling in Socket.
* Increased testcase timeout.
* Fixed unknown room emitting (GH-291). [3rd-Eden]
* Fixed `address` in handshakeData. [3rd-Eden]
* Removed transports definition in chat example.
* Fixed room cleanup
* Fixed; make sure the client is cleaned up after booting.
* Make sure to mark the client as non-open if the connection is closed.
* Removed unneeded `buffer` declarations.
* Fixed; make sure to clear socket handlers and subscriptions upon transport close.
0.7.6 / 2011-06-30
==================
* Fixed general dispatching when a client has closed.
0.7.5 / 2011-06-30
==================
* Fixed dispatching to clients that are disconnected.
0.7.4 / 2011-06-30
==================
* Fixed; only clear handlers if they were set. [level09]
0.7.3 / 2011-06-30
==================
* Exposed handshake data to clients.
* Refactored dispatcher interface.
* Changed; Moved id generation method into the manager.
* Added sub-namespace authorization. [3rd-Eden]
* Changed; normalized SocketNamespace local eventing [dvv]
* Changed; Use packet.reason or default to 'packet' [3rd-Eden]
* Changed console.error to console.log.
* Fixed; bind both servers at the same time do that the test never times out.
* Added 304 support.
* Removed `Transport#name` for abstract interface.
* Changed; lazily require http and https module only when needed. [3rd-Eden]
0.7.2 / 2011-06-22
==================
* Make sure to write a packet (of type `noop`) when closing a poll.
This solves a problem with cross-domain requests being flagged as aborted and
reconnection being triggered.
* Added `noop` message type.
0.7.1 / 2011-06-21
==================
* Fixed cross-domain XHR.
* Added CORS test to xhr-polling suite.
0.7.0 / 2010-06-21
==================
* http://socket.io/announcement.html

View File

@@ -1,6 +1,6 @@
(The MIT License)
Copyright (c) 2014-2017 Automattic <dev@cloudup.com>
Copyright (c) 2014-2018 Automattic <dev@cloudup.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -1,8 +0,0 @@
test:
@./node_modules/.bin/gulp test
test-cov:
@./node_modules/.bin/gulp test-cov
.PHONY: test

View File

@@ -7,7 +7,7 @@
[![devDependency Status](https://david-dm.org/socketio/socket.io/dev-status.svg)](https://david-dm.org/socketio/socket.io#info=devDependencies)
[![NPM version](https://badge.fury.io/js/socket.io.svg)](https://www.npmjs.com/package/socket.io)
![Downloads](https://img.shields.io/npm/dm/socket.io.svg?style=flat)
[![](http://slack.socket.io/badge.svg?)](http://slack.socket.io)
[![](https://slackin-socketio.now.sh/badge.svg)](https://slackin-socketio.now.sh)
## Features
@@ -21,6 +21,7 @@ Some implementations in other languages are also available:
- [Java](https://github.com/socketio/socket.io-client-java)
- [C++](https://github.com/socketio/socket.io-client-cpp)
- [Swift](https://github.com/socketio/socket.io-client-swift)
- [Dart](https://github.com/rikulo/socket.io-client-dart)
Its main features are:
@@ -38,7 +39,7 @@ Unless instructed otherwise a disconnected client will try to reconnect forever,
#### Disconnection detection
An heartbeat mechanism is implemented at the Engine.IO level, allowing both the server and the client to know when the other one is not responding anymore.
A heartbeat mechanism is implemented at the Engine.IO level, allowing both the server and the client to know when the other one is not responding anymore.
That functionality is achieved with timers set on both the server and the client, with timeout values (the `pingInterval` and `pingTimeout` parameters) shared during the connection handshake. Those timers require any subsequent client calls to be directed to the same server, hence the `sticky-session` requirement when using multiples nodes.

View File

@@ -23,6 +23,9 @@
- [Class: Namespace](#namespace)
- [namespace.name](#namespacename)
- [namespace.connected](#namespaceconnected)
- [namespace.adapter](#namespaceadapter)
- [namespace.to(room)](#namespacetoroom)
- [namespace.in(room)](#namespaceinroom)
- [namespace.emit(eventName[, ...args])](#namespaceemiteventname-args)
- [namespace.clients(callback)](#namespaceclientscallback)
- [namespace.use(fn)](#namespaceusefn)
@@ -30,12 +33,14 @@
- [Event: 'connection'](#event-connect)
- [Flag: 'volatile'](#flag-volatile)
- [Flag: 'local'](#flag-local)
- [Flag: 'binary'](#flag-binary)
- [Class: Socket](#socket)
- [socket.id](#socketid)
- [socket.rooms](#socketrooms)
- [socket.client](#socketclient)
- [socket.conn](#socketconn)
- [socket.request](#socketrequest)
- [socket.handshake](#sockethandshake)
- [socket.use(fn)](#socketusefn)
- [socket.send([...args][, ack])](#socketsendargs-ack)
- [socket.emit(eventName[, ...args][, ack])](#socketemiteventname-args-ack)
@@ -53,6 +58,7 @@
- [socket.disconnect(close)](#socketdisconnectclose)
- [Flag: 'broadcast'](#flag-broadcast)
- [Flag: 'volatile'](#flag-volatile-1)
- [Flag: 'binary'](#flag-binary-1)
- [Event: 'disconnect'](#event-disconnect)
- [Event: 'error'](#event-error)
- [Event: 'disconnecting'](#event-disconnecting)
@@ -73,16 +79,15 @@ Exposed by `require('socket.io')`.
- `serveClient` _(Boolean)_: whether to serve the client files (`true`)
- `adapter` _(Adapter)_: the adapter to use. Defaults to an instance of the `Adapter` that ships with socket.io which is memory based. See [socket.io-adapter](https://github.com/socketio/socket.io-adapter)
- `origins` _(String)_: the allowed origins (`*`)
- `allowRequest` _(Function)_: A function that receives a given handshake or upgrade request as its first parameter, and can decide whether to continue or not. The second argument is a function that needs to be called with the decided information: `fn(err, success)`, where `success` is a boolean value where false means that the request is rejected, and err is an error code.
- `parser` _(Parser)_: the parser to use. Defaults to an instance of the `Parser` that ships with socket.io. See [socket.io-parser](https://github.com/socketio/socket.io-parser).
Works with and without `new`:
```js
var io = require('socket.io')();
const io = require('socket.io')();
// or
var Server = require('socket.io');
var io = new Server();
const Server = require('socket.io');
const io = new Server();
```
The same options passed to socket.io are always passed to the `engine.io` `Server` that gets created. See engine.io [options](https://github.com/socketio/engine.io#methods-1) as reference.
@@ -98,6 +103,21 @@ Those two parameters will impact the delay before a client knows the server is n
**Note:** The order is important. By default, a long-polling connection is established first, and then upgraded to WebSocket if possible. Using `['websocket']` means there will be no fallback if a WebSocket connection cannot be opened.
```js
const server = require('http').createServer();
const io = require('socket.io')(server, {
path: '/test',
serveClient: false,
// below are engine.IO options
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
server.listen(3000);
```
#### new Server(port[, options])
- `port` _(Number)_ a port to listen to (a new `http.Server` will be created)
@@ -105,12 +125,50 @@ Those two parameters will impact the delay before a client knows the server is n
See [above](#new-serverhttpserver-options) for available options.
```js
const server = require('http').createServer();
const io = require('socket.io')(3000, {
path: '/test',
serveClient: false,
// below are engine.IO options
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
```
#### new Server(options)
- `options` _(Object)_
See [above](#new-serverhttpserver-options) for available options.
```js
const io = require('socket.io')({
path: '/test',
serveClient: false,
});
// either
const server = require('http').createServer();
io.attach(server, {
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
server.listen(3000);
// or
io.attach(3000, {
pingInterval: 10000,
pingTimeout: 5000,
cookie: false
});
```
#### server.sockets
* _(Namespace)_
@@ -126,10 +184,10 @@ If `value` is `true` the attached server (see `Server#attach`) will serve the cl
```js
// pass a server and the `serveClient` option
var io = require('socket.io')(http, { serveClient: false });
const io = require('socket.io')(http, { serveClient: false });
// or pass no server and then you can call the method
var io = require('socket.io')();
const io = require('socket.io')();
io.serveClient(false);
io.attach(http);
```
@@ -141,6 +199,16 @@ io.attach(http);
Sets the path `value` under which `engine.io` and the static files will be served. Defaults to `/socket.io`. If no arguments are supplied this method returns the current value.
```js
const io = require('socket.io')();
io.path('/myownpath');
// client-side
const socket = io({
path: '/myownpath'
});
```
#### server.adapter([value])
- `value` _(Adapter)_
@@ -148,24 +216,43 @@ Sets the path `value` under which `engine.io` and the static files will be serve
Sets the adapter `value`. Defaults to an instance of the `Adapter` that ships with socket.io which is memory based. See [socket.io-adapter](https://github.com/socketio/socket.io-adapter). If no arguments are supplied this method returns the current value.
```js
const io = require('socket.io')(3000);
const redis = require('socket.io-redis');
io.adapter(redis({ host: 'localhost', port: 6379 }));
```
#### server.origins([value])
- `value` _(String)_
- `value` _(String|String[])_
- **Returns** `Server|String`
Sets the allowed origins `value`. Defaults to any origins being allowed. If no arguments are supplied this method returns the current value.
```js
io.origins(['https://foo.example.com:443']);
```
#### server.origins(fn)
- `fn` _(Function)_
- **Returns** `Server`
Provides a function taking two arguments `origin:String` and `callback(error, success)`, where `success` is a boolean value indicating whether origin is allowed or not.
Provides a function taking two arguments `origin:String` and `callback(error, success)`, where `success` is a boolean value indicating whether origin is allowed or not. If `success` is set to `false`, `error` must be provided as a string value that will be appended to the server response, e.g. "Origin not allowed".
__Potential drawbacks__:
* in some situations, when it is not possible to determine `origin` it may have value of `*`
* As this function will be executed for every request, it is advised to make this function work as fast as possible
* If `socket.io` is used together with `Express`, the CORS headers will be affected only for `socket.io` requests. For Express can use [cors](https://github.com/expressjs/cors).
* If `socket.io` is used together with `Express`, the CORS headers will be affected only for `socket.io` requests. For Express you can use [cors](https://github.com/expressjs/cors).
```js
io.origins((origin, callback) => {
if (origin !== 'https://foo.example.com') {
return callback('origin not allowed', false);
}
callback(null, true);
});
```
#### server.attach(httpServer[, options])
@@ -174,7 +261,7 @@ __Potential drawbacks__:
Attaches the `Server` to an engine.io instance on `httpServer` with the supplied `options` (optionally).
### server.attach(port[, options])
#### server.attach(port[, options])
- `port` _(Number)_ the port to listen on
- `options` _(Object)_
@@ -205,11 +292,43 @@ Advanced use only. Creates a new `socket.io` client from the incoming engine.io
#### server.of(nsp)
- `nsp` _(String)_
- `nsp` _(String|RegExp|Function)_
- **Returns** `Namespace`
Initializes and retrieves the given `Namespace` by its pathname identifier `nsp`. If the namespace was already initialized it returns it immediately.
```js
const adminNamespace = io.of('/admin');
```
A regex or a function can also be provided, in order to create namespace in a dynamic way:
```js
const dynamicNsp = io.of(/^\/dynamic-\d+$/).on('connect', (socket) => {
const newNamespace = socket.nsp; // newNamespace.name === '/dynamic-101'
// broadcast to all clients in the given sub-namespace
newNamespace.emit('hello');
});
// client-side
const socket = io('/dynamic-101');
// broadcast to all clients in each sub-namespace
dynamicNsp.emit('hello');
// use a middleware for each sub-namespace
dynamicNsp.use((socket, next) => { /* ... */ });
```
With a function:
```js
io.of((name, query, next) => {
next(null, checkToken(query.token));
}).on('connect', (socket) => { /* ... */ });
```
#### server.close([callback])
- `callback` _(Function)_
@@ -217,11 +336,11 @@ Initializes and retrieves the given `Namespace` by its pathname identifier `nsp`
Closes the socket.io server. The `callback` argument is optional and will be called when all connections are closed.
```js
var Server = require('socket.io');
var PORT = 3030;
var server = require('http').Server();
const Server = require('socket.io');
const PORT = 3030;
const server = require('http').Server();
var io = Server(PORT);
const io = Server(PORT);
io.close(); // Close current server
@@ -237,7 +356,7 @@ Overwrites the default method to generate your custom socket id.
The function is called with a node request object (`http.IncomingMessage`) as first parameter.
```js
io.engine.generateId = function (req) {
io.engine.generateId = (req) => {
return "custom:id:" + custom_id++; // custom id must be unique
}
```
@@ -247,7 +366,7 @@ io.engine.generateId = function (req) {
Represents a pool of sockets connected under a given scope identified
by a pathname (eg: `/chat`).
By default the client always connects to `/`.
A client always connects to `/` (the main namespace), then potentially connect to other namespaces (while using the same underlying connection).
#### namespace.name
@@ -261,6 +380,34 @@ The namespace identifier property.
The hash of `Socket` objects that are connected to this namespace, indexed by `id`.
#### namespace.adapter
* _(Adapter)_
The `Adapter` used for the namespace. Useful when using the `Adapter` based on [Redis](https://github.com/socketio/socket.io-redis), as it exposes methods to manage sockets and rooms accross your cluster.
**Note:** the adapter of the main namespace can be accessed with `io.of('/').adapter`.
#### namespace.to(room)
- `room` _(String)_
- **Returns** `Namespace` for chaining
Sets a modifier for a subsequent event emission that the event will only be _broadcasted_ to clients that have joined the given `room`.
To emit to multiple rooms, you can call `to` several times.
```js
const io = require('socket.io')();
const adminNamespace = io.of('/admin');
adminNamespace.to('level1').emit('an event', { some: 'data' });
```
#### namespace.in(room)
Synonym of [namespace.to(room)](#namespacetoroom).
#### namespace.emit(eventName[, ...args])
- `eventName` _(String)_
@@ -269,14 +416,15 @@ The hash of `Socket` objects that are connected to this namespace, indexed by `i
Emits an event to all connected clients. The following two are equivalent:
```js
var io = require('socket.io')();
const io = require('socket.io')();
io.emit('an event sent to all connected clients'); // main namespace
var chat = io.of('/chat');
const chat = io.of('/chat');
chat.emit('an event sent to all connected clients in chat namespace');
```
**Note:** acknowledgements are not supported when emitting from namespace.
#### namespace.clients(callback)
- `callback` _(Function)_
@@ -284,8 +432,8 @@ chat.emit('an event sent to all connected clients in chat namespace');
Gets a list of client IDs connected to this namespace (across all nodes if applicable).
```js
var io = require('socket.io')();
io.of('/chat').clients(function(error, clients){
const io = require('socket.io')();
io.of('/chat').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});
@@ -294,8 +442,7 @@ io.of('/chat').clients(function(error, clients){
An example to get all clients in namespace's room:
```js
var io = require('socket.io')();
io.of('/chat').in('general').clients(function(error, clients){
io.of('/chat').in('general').clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});
@@ -304,8 +451,7 @@ io.of('/chat').in('general').clients(function(error, clients){
As with broadcasting, the default is all clients from the default namespace ('/'):
```js
var io = require('socket.io')();
io.clients(function(error, clients){
io.clients((error, clients) => {
if (error) throw error;
console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});
@@ -320,8 +466,7 @@ Registers a middleware, which is a function that gets executed for every incomin
Errors passed to middleware callbacks are sent as special `error` packets to clients.
```js
var io = require('socket.io')();
io.use(function(socket, next){
io.use((socket, next) => {
if (socket.request.headers.cookie) return next();
next(new Error('Authentication error'));
});
@@ -333,6 +478,16 @@ io.use(function(socket, next){
Fired upon a connection from client.
```js
io.on('connect', (socket) => {
// ...
});
io.of('/admin').on('connect', (socket) => {
// ...
});
```
#### Event: 'connection'
Synonym of [Event: 'connect'](#event-connect).
@@ -345,6 +500,14 @@ Sets a modifier for a subsequent event emission that the event data may be lost
io.volatile.emit('an event', { some: 'data' }); // the clients may or may not receive it
```
#### Flag: 'binary'
Specifies whether there is binary data in the emitted data. Increases performance when specified. Can be `true` or `false`.
```js
io.binary(false).emit('an event', { some: 'data' });
```
#### Flag: 'local'
Sets a modifier for a subsequent event emission that the event data will only be _broadcast_ to the current node (when the [Redis adapter](https://github.com/socketio/socket.io-redis) is used).
@@ -375,6 +538,15 @@ A unique identifier for the session, that comes from the underlying `Client`.
A hash of strings identifying the rooms this client is in, indexed by room name.
```js
io.on('connection', (socket) => {
socket.join('room 237', () => {
let rooms = Object.keys(socket.rooms);
console.log(rooms); // [ <socket.id>, 'room 237' ]
});
});
```
#### socket.client
* _(Client)_
@@ -393,6 +565,39 @@ A reference to the underlying `Client` transport connection (engine.io `Socket`
A getter proxy that returns the reference to the `request` that originated the underlying engine.io `Client`. Useful for accessing request headers such as `Cookie` or `User-Agent`.
#### socket.handshake
* _(Object)_
The handshake details:
```js
{
headers: /* the headers sent as part of the handshake */,
time: /* the date of creation (as string) */,
address: /* the ip of the client */,
xdomain: /* whether the connection is cross-domain */,
secure: /* whether the connection is secure */,
issued: /* the date of creation (as unix timestamp) */,
url: /* the request URL string */,
query: /* the query object */
}
```
Usage:
```js
io.use((socket, next) => {
let handshake = socket.handshake;
// ...
});
io.on('connection', (socket) => {
let handshake = socket.handshake;
// ...
});
```
#### socket.use(fn)
- `fn` _(Function)_
@@ -402,9 +607,8 @@ Registers a middleware, which is a function that gets executed for every incomin
Errors passed to middleware callbacks are sent as special `error` packets to clients.
```js
var io = require('socket.io')();
io.on('connection', function(socket){
socket.use(function(packet, next){
io.on('connection', (socket) => {
socket.use((packet, next) => {
if (packet.doge === true) return next();
next(new Error('Not a doge error'));
});
@@ -437,16 +641,15 @@ socket.emit('with-binary', 1, '2', { 3: '4', 5: new Buffer(6) });
The `ack` argument is optional and will be called with the client's answer.
```js
var io = require('socket.io')();
io.on('connection', function(client){
client.emit('an event', { some: 'data' });
io.on('connection', (socket) => {
socket.emit('an event', { some: 'data' });
client.emit('ferret', 'tobi', function (data) {
socket.emit('ferret', 'tobi', (data) => {
console.log(data); // data will be 'woot'
});
// the client code
// client.on('ferret', function (name, fn) {
// client.on('ferret', (name, fn) => {
// fn('woot');
// });
@@ -463,9 +666,17 @@ io.on('connection', function(client){
Register a new handler for the given event.
```js
socket.on('news', function (data) {
socket.on('news', (data) => {
console.log(data);
});
// with several arguments
socket.on('news', (arg1, arg2, arg3) => {
// ...
});
// or with acknowledgement
socket.on('news', (data, callback) => {
callback(0);
});
```
#### socket.once(eventName, listener)
@@ -484,23 +695,24 @@ Inherited from `EventEmitter` (along with other methods not mentioned here). See
Adds the client to the `room`, and fires optionally a callback with `err` signature (if any).
```js
io.on('connection', function(socket){
socket.join('room 237', function(){
console.log(socket.rooms); // [ <socket.id>, 'room 237' ]
io.to('room 237', 'a new user has joined the room'); // broadcast to everyone in the room
io.on('connection', (socket) => {
socket.join('room 237', () => {
let rooms = Object.keys(socket.rooms);
console.log(rooms); // [ <socket.id>, 'room 237' ]
io.to('room 237').emit('a new user has joined the room'); // broadcast to everyone in the room
});
});
```
The mechanics of joining rooms are handled by the `Adapter` that has been configured (see `Server#adapter` above), defaulting to [socket.io-adapter](https://github.com/socketio/socket.io-adapter).
For your convenience, each socket automatically joins a room identified by this id (see `Socket#id`). This makes it easy to broadcast messages to other sockets:
For your convenience, each socket automatically joins a room identified by its id (see `Socket#id`). This makes it easy to broadcast messages to other sockets:
```js
io.on('connection', function(client){
client.on('say to someone', function(id, msg){
io.on('connection', (socket) => {
socket.on('say to someone', (id, msg) => {
// send a private message to the socket with the given id
client.broadcast.to(id).emit('my message', msg);
socket.to(id).emit('my message', msg);
});
});
```
@@ -528,20 +740,23 @@ Removes the client from `room`, and fires optionally a callback with `err` signa
- `room` _(String)_
- **Returns** `Socket` for chaining
Sets a modifier for a subsequent event emission that the event will only be _broadcasted_ to clients that have joined the given `room`.
Sets a modifier for a subsequent event emission that the event will only be _broadcasted_ to clients that have joined the given `room` (the socket itself being excluded).
To emit to multiple rooms, you can call `to` several times.
```js
var io = require('socket.io')();
io.on('connection', function(client){
io.on('connection', (socket) => {
// to one room
client.to('others').emit('an event', { some: 'data' });
socket.to('others').emit('an event', { some: 'data' });
// to multiple rooms
client.to('room1').to('room2').emit('hello');
socket.to('room1').to('room2').emit('hello');
// a private message to another socket
socket.to(/* another socket id */).emit('hey');
});
```
**Note:** acknowledgements are not supported when broadcasting.
#### socket.in(room)
Synonym of [socket.to(room)](#sockettoroom).
@@ -553,6 +768,12 @@ Synonym of [socket.to(room)](#sockettoroom).
Sets a modifier for a subsequent event emission that the event data will only be _compressed_ if the value is `true`. Defaults to `true` when you don't call the method.
```js
io.on('connection', (socket) => {
socket.compress(false).emit('uncompressed', "that's rough");
});
```
#### socket.disconnect(close)
- `close` _(Boolean)_ whether to close the underlying connection
@@ -560,13 +781,18 @@ Sets a modifier for a subsequent event emission that the event data will only be
Disconnects this client. If value of close is `true`, closes the underlying connection. Otherwise, it just disconnects the namespace.
```js
io.on('connection', (socket) => {
setTimeout(() => socket.disconnect(true), 5000);
});
```
#### Flag: 'broadcast'
Sets a modifier for a subsequent event emission that the event data will only be _broadcast_ to every sockets but the sender.
```js
var io = require('socket.io')();
io.on('connection', function(socket){
io.on('connection', (socket) => {
socket.broadcast.emit('an event', { some: 'data' }); // everyone gets it but the sender
});
```
@@ -575,10 +801,20 @@ io.on('connection', function(socket){
Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to receive messages (because of network slowness or other issues, or because theyre connected through long polling and is in the middle of a request-response cycle).
```js
io.on('connection', (socket) => {
socket.volatile.emit('an event', { some: 'data' }); // the client may or may not receive it
});
```
#### Flag: 'binary'
Specifies whether there is binary data in the emitted data. Increases performance when specified. Can be `true` or `false`.
```js
var io = require('socket.io')();
io.on('connection', function(socket){
socket.volatile.emit('an event', { some: 'data' }); // the client may or may not receive it
socket.binary(false).emit('an event', { some: 'data' }); // The data to send has no binary data
});
```
@@ -588,18 +824,43 @@ io.on('connection', function(socket){
Fired upon disconnection.
```js
io.on('connection', (socket) => {
socket.on('disconnect', (reason) => {
// ...
});
});
```
#### Event: 'error'
- `error` _(Object)_ error object
Fired when an error occurs.
```js
io.on('connection', (socket) => {
socket.on('error', (error) => {
// ...
});
});
```
#### Event: 'disconnecting'
- `reason` _(String)_ the reason of the disconnection (either client or server-side)
Fired when the client is going to be disconnected (but hasn't left its `rooms` yet).
```js
io.on('connection', (socket) => {
socket.on('disconnecting', (reason) => {
let rooms = Object.keys(socket.rooms);
// ...
});
});
```
These are reserved events (along with `connect`, `newListener` and `removeListener`) which cannot be used as event names.
### Client

View File

@@ -29,7 +29,7 @@ function onConnect(socket){
io.of('myNamespace').to('room').emit('event', 'message');
// sending to individual socketid (private message)
socket.to(<socketid>).emit('hey', 'I just met you');
io.to(<socketid>).emit('hey', 'I just met you');
// sending with acknowledgement
socket.emit('question', 'do you think so?', function (answer) {});
@@ -40,9 +40,15 @@ function onConnect(socket){
// sending a message that might be dropped if the client is not ready to receive messages
socket.volatile.emit('maybe', 'do you really need it?');
// specifying whether the data to send has binary data
socket.binary(false).emit('what', 'I have no binaries!');
// sending to all clients on this node (when using multiple nodes)
io.local.emit('hi', 'my lovely babies');
// sending to all connected clients
io.emit('an event sent to all connected clients');
};
```

View File

@@ -1,26 +1,27 @@
// Setup basic express server
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
// Chatroom
var numUsers = 0;
io.on('connection', function (socket) {
io.on('connection', (socket) => {
var addedUser = false;
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
socket.on('new message', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
@@ -29,7 +30,7 @@ io.on('connection', function (socket) {
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
socket.on('add user', (username) => {
if (addedUser) return;
// we store the username in the socket session for this client
@@ -47,21 +48,21 @@ io.on('connection', function (socket) {
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.on('typing', () => {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.on('stop typing', () => {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
socket.on('disconnect', () => {
if (addedUser) {
--numUsers;

View File

@@ -25,7 +25,7 @@ $(function() {
var socket = io();
function addParticipantsMessage (data) {
const addParticipantsMessage = (data) => {
var message = '';
if (data.numUsers === 1) {
message += "there's 1 participant";
@@ -36,7 +36,7 @@ $(function() {
}
// Sets the client's username
function setUsername () {
const setUsername = () => {
username = cleanInput($usernameInput.val().trim());
// If the username is valid
@@ -52,7 +52,7 @@ $(function() {
}
// Sends a chat message
function sendMessage () {
const sendMessage = () => {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
@@ -69,13 +69,13 @@ $(function() {
}
// Log a message
function log (message, options) {
const log = (message, options) => {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
const addChatMessage = (data, options) => {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessages(data);
options = options || {};
@@ -100,15 +100,15 @@ $(function() {
}
// Adds the visual chat typing message
function addChatTyping (data) {
const addChatTyping = (data) => {
data.typing = true;
data.message = 'is typing';
addChatMessage(data);
}
// Removes the visual chat typing message
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
const removeChatTyping = (data) => {
getTypingMessages(data).fadeOut(() => {
$(this).remove();
});
}
@@ -118,7 +118,7 @@ $(function() {
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
const addMessageElement = (el, options) => {
var $el = $(el);
// Setup default options
@@ -145,12 +145,12 @@ $(function() {
}
// Prevents input from having injected markup
function cleanInput (input) {
return $('<div/>').text(input).text();
const cleanInput = (input) => {
return $('<div/>').text(input).html();
}
// Updates the typing event
function updateTyping () {
const updateTyping = () => {
if (connected) {
if (!typing) {
typing = true;
@@ -158,7 +158,7 @@ $(function() {
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
setTimeout(() => {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
@@ -170,14 +170,14 @@ $(function() {
}
// Gets the 'X is typing' messages of a user
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
const getTypingMessages = (data) => {
return $('.typing.message').filter(i => {
return $(this).data('username') === data.username;
});
}
// Gets the color of a username through our hash function
function getUsernameColor (username) {
const getUsernameColor = (username) => {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
@@ -190,7 +190,7 @@ $(function() {
// Keyboard events
$window.keydown(function (event) {
$window.keydown(event => {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
@@ -207,26 +207,26 @@ $(function() {
}
});
$inputMessage.on('input', function() {
$inputMessage.on('input', () => {
updateTyping();
});
// Click events
// Focus input when clicking anywhere on login page
$loginPage.click(function () {
$loginPage.click(() => {
$currentInput.focus();
});
// Focus input when clicking on the message input's border
$inputMessage.click(function () {
$inputMessage.click(() => {
$inputMessage.focus();
});
// Socket events
// Whenever the server emits 'login', log the login message
socket.on('login', function (data) {
socket.on('login', (data) => {
connected = true;
// Display the welcome message
var message = "Welcome to Socket.IO Chat ";
@@ -237,45 +237,45 @@ $(function() {
});
// Whenever the server emits 'new message', update the chat body
socket.on('new message', function (data) {
socket.on('new message', (data) => {
addChatMessage(data);
});
// Whenever the server emits 'user joined', log it in the chat body
socket.on('user joined', function (data) {
socket.on('user joined', (data) => {
log(data.username + ' joined');
addParticipantsMessage(data);
});
// Whenever the server emits 'user left', log it in the chat body
socket.on('user left', function (data) {
socket.on('user left', (data) => {
log(data.username + ' left');
addParticipantsMessage(data);
removeChatTyping(data);
});
// Whenever the server emits 'typing', show the typing message
socket.on('typing', function (data) {
socket.on('typing', (data) => {
addChatTyping(data);
});
// Whenever the server emits 'stop typing', kill the typing message
socket.on('stop typing', function (data) {
socket.on('stop typing', (data) => {
removeChatTyping(data);
});
socket.on('disconnect', function () {
socket.on('disconnect', () => {
log('you have been disconnected');
});
socket.on('reconnect', function () {
socket.on('reconnect', () => {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
socket.on('reconnect_error', () => {
log('attempt to reconnect has failed');
});

View File

@@ -1,7 +1,8 @@
const server = require('http').createServer();
const io = require('socket.io')(server, {
// serveClient: false // do not serve the client file, in that case the brfs loader is not needed
serveClient: false,
wsEngine: 'ws' // uws is not supported since it is a native module
});
const port = process.env.PORT || 3000;

View File

@@ -8,16 +8,8 @@
},
"author": "Damien Arrachequesne",
"license": "MIT",
"dependencies": {
"brfs": "^1.4.3",
"bufferutil": "^1.3.0",
"socket.io": "^1.7.2",
"transform-loader": "^0.2.3",
"utf-8-validate": "^2.0.0"
},
"devDependencies": {
"json-loader": "^0.5.4",
"null-loader": "^0.1.1",
"webpack": "^1.14.0"
"socket.io": "^2.0.3",
"webpack": "^2.6.1"
}
}

View File

@@ -3,23 +3,7 @@ module.exports = {
entry: './lib/index.js',
target: 'node',
output: {
path: './dist',
path: require('path').join(__dirname, '../dist'),
filename: 'server.js'
},
module: {
loaders: [
{
test: /(\.md|\.map)$/,
loader: 'null'
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.js$/,
loader: "transform-loader?brfs"
}
]
}
};

View File

@@ -1,5 +1,7 @@
var socket = require('socket.io-client')('http://localhost:3000');
import io from 'socket.io-client';
const socket = io('http://localhost:3000');
console.log('init');

View File

@@ -5,15 +5,17 @@
"scripts": {
"build": "webpack --config ./support/webpack.config.js",
"build-slim": "webpack --config ./support/webpack.config.slim.js",
"build-all": "npm run build && npm run build-slim"
"build-json-parser": "webpack --config ./support/webpack.config.json-parser.js",
"build-all": "npm run build && npm run build-slim && npm run build-json-parser"
},
"author": "Damien Arrachequesne",
"license": "MIT",
"dependencies": {
"socket.io-client": "^1.7.2"
"socket.io-client": "^2.0.2",
"socket.io-json-parser": "^2.1.0"
},
"devDependencies": {
"strip-loader": "^0.1.2",
"webpack": "^1.14.0"
"webpack": "^2.6.1"
}
}

View File

@@ -2,7 +2,7 @@
module.exports = {
entry: './lib/index.js',
output: {
path: './dist',
path: require('path').join(__dirname, '../dist'),
filename: 'app.js'
},
}
};

View File

@@ -0,0 +1,33 @@
var webpack = require('webpack');
module.exports = {
entry: './lib/index.js',
output: {
path: require('path').join(__dirname, '../dist'),
filename: 'app.json-parser.js'
},
// generate sourcemap
devtool: 'source-map',
plugins: [
// replace require('debug')() with an noop function
new webpack.NormalModuleReplacementPlugin(/debug/, process.cwd() + '/support/noop.js'),
// replace socket.io-parser with socket.io-json-parser
new webpack.NormalModuleReplacementPlugin(/socket\.io-parser/, 'socket.io-json-parser'),
// use uglifyJS (IE9+ support)
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
],
module: {
loaders: [
{
// strip `debug()` calls
test: /\.js$/,
loader: 'strip-loader?strip[]=debug'
}
]
}
};

View File

@@ -4,13 +4,9 @@ var webpack = require('webpack');
module.exports = {
entry: './lib/index.js',
output: {
path: './dist',
path: require('path').join(__dirname, '../dist'),
filename: 'app.slim.js'
},
externals: {
// replace JSON polyfill (IE6/IE7) with global JSON object
json3: 'JSON'
},
// generate sourcemap
devtool: 'source-map',
plugins: [

View File

@@ -1,69 +0,0 @@
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const babel = require("gulp-babel");
const istanbul = require('gulp-istanbul');
const help = require('gulp-task-listing');
const del = require('del');
gulp.task('help', help);
gulp.task('default', ['transpile']);
const TRANSPILE_DEST_DIR = './dist';
// By default, individual js files are transformed by babel and exported to /dist
gulp.task('transpile', function () {
return gulp.src("lib/*.js")
.pipe(babel({ "presets": ["es2015"] }))
.pipe(gulp.dest(TRANSPILE_DEST_DIR));
});
gulp.task('clean', function () {
return del([TRANSPILE_DEST_DIR]);
})
gulp.task('test', ['transpile'], function(){
return gulp.src('test/socket.io.js', {read: false})
.pipe(mocha({
slow: 200,
reporter: 'spec',
bail: true,
timeout: 10000
}))
.once('error', function (err) {
console.error(err.stack);
process.exit(1);
})
.once('end', function () {
process.exit();
});
});
gulp.task('set-compat-node-env', function() {
process.env.TEST_VERSION = 'compat';
});
gulp.task('test-compat', ['set-compat-node-env', 'test']);
gulp.task('istanbul-pre-test', function () {
return gulp.src(['lib/**/*.js'])
// Covering files
.pipe(istanbul())
// Force `require` to return covered files
.pipe(istanbul.hookRequire());
});
gulp.task('test-cov', ['istanbul-pre-test'], function(){
return gulp.src('test/socket.io.js', {read: false})
.pipe(mocha({
reporter: 'dot'
}))
.pipe(istanbul.writeReports())
.once('error', function (err){
console.error(err.stack);
process.exit(1);
})
.once('end', function (){
process.exit();
});
});

View File

@@ -56,17 +56,38 @@ Client.prototype.setup = function(){
* Connects a client to a namespace.
*
* @param {String} name namespace
* @param {Object} query the query parameters
* @api private
*/
Client.prototype.connect = function(name, query){
debug('connecting to namespace %s', name);
var nsp = this.server.nsps[name];
if (!nsp) {
this.packet({ type: parser.ERROR, nsp: name, data : 'Invalid namespace'});
return;
if (this.server.nsps[name]) {
debug('connecting to namespace %s', name);
return this.doConnect(name, query);
}
this.server.checkNamespace(name, query, (dynamicNsp) => {
if (dynamicNsp) {
debug('dynamic namespace %s was created', dynamicNsp.name);
this.doConnect(name, query);
} else {
debug('creation of namespace %s was denied', name);
this.packet({ type: parser.ERROR, nsp: name, data: 'Invalid namespace' });
}
});
};
/**
* Connects a client to a namespace.
*
* @param {String} name namespace
* @param {String} query the query parameters
* @api private
*/
Client.prototype.doConnect = function(name, query){
var nsp = this.server.of(name);
if ('/' != name && !this.nsps['/']) {
this.connectBuffer.push(name);
return;

View File

@@ -1,3 +1,4 @@
'use strict';
/**
* Module dependencies.
@@ -8,11 +9,11 @@ var read = require('fs').readFileSync;
var path = require('path');
var exists = require('fs').existsSync;
var engine = require('engine.io');
var client = require('socket.io-client');
var clientVersion = require('socket.io-client/package').version;
var clientVersion = require('socket.io-client/package.json').version;
var Client = require('./client');
var Emitter = require('events').EventEmitter;
var Namespace = require('./namespace');
var ParentNamespace = require('./parent-namespace');
var Adapter = require('socket.io-adapter');
var parser = require('socket.io-parser');
var debug = require('debug')('socket.io:server');
@@ -47,6 +48,7 @@ function Server(srv, opts){
}
opts = opts || {};
this.nsps = {};
this.parentNsps = new Map();
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.parser = opts.parser || parser;
@@ -80,9 +82,11 @@ Server.prototype.checkRequest = function(req, fn) {
? parts.port
: defaultPort;
var ok =
~this._origins.indexOf(parts.protocol + '//' + parts.hostname + ':' + parts.port) ||
~this._origins.indexOf(parts.hostname + ':' + parts.port) ||
~this._origins.indexOf(parts.hostname + ':*') ||
~this._origins.indexOf('*:' + parts.port);
debug('origin %s is %svalid', origin, !!ok ? '' : 'not ');
return fn(null, !!ok);
} catch (ex) {
}
@@ -158,6 +162,37 @@ Server.prototype.set = function(key, val){
return this;
};
/**
* Executes the middleware for an incoming namespace not already created on the server.
*
* @param {String} name name of incoming namespace
* @param {Object} query the query parameters
* @param {Function} fn callback
* @api private
*/
Server.prototype.checkNamespace = function(name, query, fn){
if (this.parentNsps.size === 0) return fn(false);
const keysIterator = this.parentNsps.keys();
const run = () => {
let nextFn = keysIterator.next();
if (nextFn.done) {
return fn(false);
}
nextFn.value(name, query, (err, allow) => {
if (err || !allow) {
run();
} else {
fn(this.parentNsps.get(nextFn.value).createChild(name));
}
});
};
run();
};
/**
* Sets the client serving path.
*
@@ -194,7 +229,7 @@ Server.prototype.adapter = function(v){
/**
* Sets the allowed origins for requests.
*
* @param {String} v origins
* @param {String|String[]} v origins
* @return {Server|Adapter} self when setting or value when getting
* @api public
*/
@@ -245,31 +280,45 @@ Server.prototype.attach = function(srv, opts){
// set origins verification
opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this);
var self = this;
if (this.sockets.fns.length > 0) {
this.initEngine(srv, opts);
return this;
}
var self = this;
var connectPacket = { type: parser.CONNECT, nsp: '/' };
this.encoder.encode(connectPacket, function (encodedPacket){
// the CONNECT packet will be merged with Engine.IO handshake,
// to reduce the number of round trips
opts.initialPacket = encodedPacket;
// initialize engine
debug('creating engine.io instance with opts %j', opts);
self.eio = engine.attach(srv, opts);
// attach static file serving
if (self._serveClient) self.attachServe(srv);
// Export http server
self.httpServer = srv;
// bind to engine events
self.bind(self.eio);
self.initEngine(srv, opts);
});
return this;
};
/**
* Initialize engine
*
* @param {Object} options passed to engine.io
* @api private
*/
Server.prototype.initEngine = function(srv, opts){
// initialize engine
debug('creating engine.io instance with opts %j', opts);
this.eio = engine.attach(srv, opts);
// attach static file serving
if (this._serveClient) this.attachServe(srv);
// Export http server
this.httpServer = srv;
// bind to engine events
this.bind(this.eio);
};
/**
* Attaches the static file serving.
*
@@ -389,12 +438,24 @@ Server.prototype.onconnection = function(conn){
/**
* Looks up a namespace.
*
* @param {String} name nsp name
* @param {String|RegExp|Function} name nsp name
* @param {Function} [fn] optional, nsp `connection` ev handler
* @api public
*/
Server.prototype.of = function(name, fn){
if (typeof name === 'function' || name instanceof RegExp) {
const parentNsp = new ParentNamespace(this);
debug('initializing parent namespace %s', parentNsp.name);
if (typeof name === 'function') {
this.parentNsps.set(name, parentNsp);
} else {
this.parentNsps.set((nsp, conn, next) => next(null, name.test(nsp)), parentNsp);
}
if (fn) parentNsp.on('connect', fn);
return parentNsp;
}
if (String(name)[0] !== '/') name = '/' + name;
var nsp = this.nsps[name];
@@ -438,7 +499,7 @@ var emitterMethods = Object.keys(Emitter.prototype).filter(function(key){
return typeof Emitter.prototype[key] === 'function';
});
emitterMethods.concat(['to', 'in', 'use', 'send', 'write', 'clients', 'compress']).forEach(function(fn){
emitterMethods.concat(['to', 'in', 'use', 'send', 'write', 'clients', 'compress', 'binary']).forEach(function(fn){
Server.prototype[fn] = function(){
return this.sockets[fn].apply(this.sockets, arguments);
};

View File

@@ -6,6 +6,7 @@
var Socket = require('./socket');
var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');
var hasBin = require('has-binary2');
var debug = require('debug')('socket.io:namespace');
/**
@@ -99,6 +100,10 @@ Namespace.prototype.initAdapter = function(){
*/
Namespace.prototype.use = function(fn){
if (this.server.eio && this.name === '/') {
debug('removing initial packet');
delete this.server.eio.initialPacket;
}
this.fns.push(fn);
return this;
};
@@ -206,23 +211,31 @@ Namespace.prototype.remove = function(socket){
Namespace.prototype.emit = function(ev){
if (~exports.events.indexOf(ev)) {
emit.apply(this, arguments);
} else {
// set up packet object
var args = Array.prototype.slice.call(arguments);
var packet = { type: parser.EVENT, data: args };
if ('function' == typeof args[args.length - 1]) {
throw new Error('Callbacks are not supported when broadcasting');
}
this.adapter.broadcast(packet, {
rooms: this.rooms,
flags: this.flags
});
this.rooms = [];
this.flags = {};
return this;
}
// set up packet object
var args = Array.prototype.slice.call(arguments);
var packet = {
type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
data: args
};
if ('function' == typeof args[args.length - 1]) {
throw new Error('Callbacks are not supported when broadcasting');
}
var rooms = this.rooms.slice(0);
var flags = Object.assign({}, this.flags);
// reset flags
this.rooms = [];
this.flags = {};
this.adapter.broadcast(packet, {
rooms: rooms,
flags: flags
});
return this;
};
@@ -268,3 +281,16 @@ Namespace.prototype.compress = function(compress){
this.flags.compress = compress;
return this;
};
/**
* Sets the binary flag
*
* @param {Boolean} Encode as if it has binary data if `true`, Encode as if it doesnt have binary data if `false`
* @return {Socket} self
* @api public
*/
Namespace.prototype.binary = function (binary) {
this.flags.binary = binary;
return this;
};

39
lib/parent-namespace.js Normal file
View File

@@ -0,0 +1,39 @@
'use strict';
const Namespace = require('./namespace');
let count = 0;
class ParentNamespace extends Namespace {
constructor(server) {
super(server, '/_' + (count++));
this.children = new Set();
}
initAdapter() {}
emit() {
const args = Array.prototype.slice.call(arguments);
this.children.forEach(nsp => {
nsp.rooms = this.rooms;
nsp.flags = this.flags;
nsp.emit.apply(nsp, args);
});
this.rooms = [];
this.flags = {};
}
createChild(name) {
const namespace = new Namespace(this.server, name);
namespace.fns = this.fns.slice(0);
this.listeners('connect').forEach(listener => namespace.on('connect', listener));
this.listeners('connection').forEach(listener => namespace.on('connection', listener));
this.children.add(namespace);
this.server.nsps[name] = namespace;
return namespace;
}
}
module.exports = ParentNamespace;

View File

@@ -5,9 +5,9 @@
var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');
var hasBin = require('has-binary2');
var url = require('url');
var debug = require('debug')('socket.io:socket');
var assign = require('object-assign');
/**
* Module exports.
@@ -39,7 +39,8 @@ exports.events = [
var flags = [
'json',
'volatile',
'broadcast'
'broadcast',
'local'
];
/**
@@ -115,7 +116,7 @@ Socket.prototype.buildHandshake = function(query){
function buildQuery(){
var requestQuery = url.parse(self.request.url, true).query;
//if socket-specific query exist, replace query strings in requestQuery
return assign({}, query, requestQuery);
return Object.assign({}, query, requestQuery);
}
return {
headers: this.request.headers,
@@ -139,38 +140,42 @@ Socket.prototype.buildHandshake = function(query){
Socket.prototype.emit = function(ev){
if (~exports.events.indexOf(ev)) {
emit.apply(this, arguments);
} else {
var args = Array.prototype.slice.call(arguments);
var packet = {
type: parser.EVENT,
data: args
};
return this;
}
// access last argument to see if it's an ACK callback
if (typeof args[args.length - 1] === 'function') {
if (this._rooms.length || this.flags.broadcast) {
throw new Error('Callbacks are not supported when broadcasting');
}
debug('emitting packet with ack id %d', this.nsp.ids);
this.acks[this.nsp.ids] = args.pop();
packet.id = this.nsp.ids++;
}
var args = Array.prototype.slice.call(arguments);
var packet = {
type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
data: args
};
// access last argument to see if it's an ACK callback
if (typeof args[args.length - 1] === 'function') {
if (this._rooms.length || this.flags.broadcast) {
this.adapter.broadcast(packet, {
except: [this.id],
rooms: this._rooms,
flags: this.flags
});
} else {
// dispatch packet
this.packet(packet, this.flags);
throw new Error('Callbacks are not supported when broadcasting');
}
// reset flags
this._rooms = [];
this.flags = {};
debug('emitting packet with ack id %d', this.nsp.ids);
this.acks[this.nsp.ids] = args.pop();
packet.id = this.nsp.ids++;
}
var rooms = this._rooms.slice(0);
var flags = Object.assign({}, this.flags);
// reset flags
this._rooms = [];
this.flags = {};
if (rooms.length || flags.broadcast) {
this.adapter.broadcast(packet, {
except: [this.id],
rooms: rooms,
flags: flags
});
} else {
// dispatch packet
this.packet(packet, flags);
}
return this;
};
@@ -297,9 +302,10 @@ Socket.prototype.onconnect = function(){
debug('socket connected - writing packet');
this.nsp.connected[this.id] = this;
this.join(this.id);
// the CONNECT packet for the default namespace
// has already been sent as an `initialPacket`
if (this.nsp.name !== '/') {
var skip = this.nsp.name === '/' && this.nsp.fns.length === 0;
if (skip) {
debug('packet already sent in initial handshake');
} else {
this.packet({ type: parser.CONNECT });
}
};
@@ -335,7 +341,7 @@ Socket.prototype.onpacket = function(packet){
break;
case parser.ERROR:
this.emit('error', packet.data);
this.onerror(new Error(packet.data));
}
};
@@ -376,7 +382,7 @@ Socket.prototype.ack = function(id){
self.packet({
id: id,
type: parser.ACK,
type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
data: args
});
@@ -491,6 +497,19 @@ Socket.prototype.compress = function(compress){
return this;
};
/**
* Sets the binary flag
*
* @param {Boolean} Encode as if it has binary data if `true`, Encode as if it doesnt have binary data if `false`
* @return {Socket} self
* @api public
*/
Socket.prototype.binary = function (binary) {
this.flags.binary = binary;
return this;
};
/**
* Dispatch incoming event to socket listeners.
*

View File

@@ -1,6 +1,6 @@
{
"name": "socket.io",
"version": "2.0.1",
"version": "2.1.1",
"description": "node.js realtime framework server",
"keywords": [
"realtime",
@@ -21,29 +21,22 @@
"url": "git://github.com/socketio/socket.io"
},
"scripts": {
"test": "gulp test"
"test": "nyc mocha --reporter spec --slow 200 --bail --timeout 10000 test/socket.io.js"
},
"dependencies": {
"debug": "~2.6.6",
"engine.io": "~3.1.0",
"object-assign": "~4.1.1",
"debug": "~3.1.0",
"engine.io": "~3.2.0",
"has-binary2": "~1.0.2",
"socket.io-adapter": "~1.1.0",
"socket.io-client": "2.0.1",
"socket.io-parser": "~3.1.1"
"socket.io-client": "2.1.1",
"socket.io-parser": "~3.2.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"del": "^2.2.2",
"expect.js": "0.3.1",
"gulp": "^3.9.1",
"gulp-babel": "^6.1.2",
"gulp-istanbul": "^1.1.1",
"gulp-mocha": "^4.3.1",
"gulp-task-listing": "1.0.1",
"istanbul": "^0.4.5",
"mocha": "^3.3.0",
"superagent": "1.6.1",
"supertest": "1.1.0"
"mocha": "^3.5.3",
"nyc": "^11.2.1",
"superagent": "^3.8.2",
"supertest": "^3.0.0"
},
"contributors": [
{

View File

@@ -1,12 +1,7 @@
var testVersion = process.env.TEST_VERSION;
'use strict';
var http = require('http').Server;
var io;
if (testVersion === 'compat') {
console.log('testing compat version');
io = require('../dist');
} else {
io = require('../lib');
}
var io = require('../lib');
var fs = require('fs');
var join = require('path').join;
var exec = require('child_process').exec;
@@ -87,6 +82,9 @@ describe('socket.io', function(){
srv.set('authorization', function(o, f) { f(null, false); });
var socket = client(httpSrv);
socket.on('connect', function(){
expect().fail();
});
socket.on('error', function(err) {
expect(err).to.be('Not authorized');
done();
@@ -358,6 +356,17 @@ describe('socket.io', function(){
done();
});
});
it('should allow request when using an array of origins', function(done) {
io({ origins: [ 'http://foo.example:54024' ] }).listen('54024');
request.get('http://localhost:54024/socket.io/default/')
.set('origin', 'http://foo.example:54024')
.query({ transport: 'polling' })
.end(function (err, res) {
expect(res.status).to.be(200);
done();
});
});
});
describe('close', function(){
@@ -429,18 +438,9 @@ describe('socket.io', function(){
});
describe('namespaces', function(){
var Socket;
if (testVersion === 'compat') {
Socket = require('../dist/socket');
} else {
Socket = require('../lib/socket');
}
var Namespace;
if (testVersion === 'compat') {
Namespace = require('../dist/namespace');
} else {
Namespace = require('../lib/namespace');
}
var Socket = require('../lib/socket');
var Namespace = require('../lib/namespace');
it('should be accessible through .sockets', function(){
var sio = io();
expect(sio.sockets).to.be.a(Namespace);
@@ -891,6 +891,61 @@ describe('socket.io', function(){
});
});
});
describe('dynamic namespaces', function () {
it('should allow connections to dynamic namespaces with a regex', function(done){
const srv = http();
const sio = io(srv);
let count = 0;
srv.listen(function(){
const socket = client(srv, '/dynamic-101');
let dynamicNsp = sio.of(/^\/dynamic-\d+$/).on('connect', (socket) => {
expect(socket.nsp.name).to.be('/dynamic-101');
dynamicNsp.emit('hello', 1, '2', { 3: '4'});
if (++count === 4) done();
}).use((socket, next) => {
next();
if (++count === 4) done();
});
socket.on('error', function(err) {
expect().fail();
});
socket.on('connect', () => {
if (++count === 4) done();
});
socket.on('hello', (a, b, c) => {
expect(a).to.eql(1);
expect(b).to.eql('2');
expect(c).to.eql({ 3: '4' });
if (++count === 4) done();
});
});
});
it('should allow connections to dynamic namespaces with a function', function(done){
const srv = http();
const sio = io(srv);
srv.listen(function(){
const socket = client(srv, '/dynamic-101');
sio.of((name, query, next) => next(null, '/dynamic-101' === name));
socket.on('connect', done);
});
});
it('should disallow connections when no dynamic namespace matches', function(done){
const srv = http();
const sio = io(srv);
srv.listen(function(){
const socket = client(srv, '/abc');
sio.of(/^\/dynamic-\d+$/);
sio.of((name, query, next) => next(null, '/dynamic-101' === name));
socket.on('error', (err) => {
expect(err).to.be('Invalid namespace');
done();
});
});
});
});
});
describe('socket', function(){
@@ -1686,7 +1741,7 @@ describe('socket.io', function(){
var socket = client(srv, { reconnection: false });
sio.on('connection', function(s){
s.conn.on('upgrade', function(){
console.log('\033[96mNote: warning expected and normal in test.\033[39m');
console.log('\u001b[96mNote: warning expected and normal in test.\u001b[39m');
socket.io.engine.write('5woooot');
setTimeout(function(){
done();
@@ -1696,6 +1751,23 @@ describe('socket.io', function(){
});
});
it('should not crash when receiving an error packet without handler', function(done){
var srv = http();
var sio = io(srv);
srv.listen(function(){
var socket = client(srv, { reconnection: false });
sio.on('connection', function(s){
s.conn.on('upgrade', function(){
console.log('\u001b[96mNote: warning expected and normal in test.\u001b[39m');
socket.io.engine.write('44["handle me please"]');
setTimeout(function(){
done();
}, 100);
});
});
});
});
it('should not crash with raw binary', function(done){
var srv = http();
var sio = io(srv);
@@ -2103,12 +2175,7 @@ describe('socket.io', function(){
});
describe('middleware', function(done){
var Socket;
if (testVersion === 'compat') {
Socket = require('../dist/socket');
} else {
Socket = require('../lib/socket');
}
var Socket = require('../lib/socket');
it('should call functions', function(done){
var srv = http();
@@ -2145,6 +2212,9 @@ describe('socket.io', function(){
});
srv.listen(function(){
var socket = client(srv);
socket.on('connect', function(){
done(new Error('nope'));
});
socket.on('error', function(err){
expect(err).to.be('Authentication error');
done();
@@ -2163,6 +2233,9 @@ describe('socket.io', function(){
});
srv.listen(function(){
var socket = client(srv);
socket.on('connect', function(){
done(new Error('nope'));
});
socket.on('error', function(err){
expect(err).to.eql({ a: 'b', c: 3 });
done();
@@ -2186,6 +2259,26 @@ describe('socket.io', function(){
});
});
it('should only call connection after (lengthy) fns', function(done){
var srv = http();
var sio = io(srv);
var authenticated = false;
sio.use(function(socket, next){
setTimeout(function () {
authenticated = true;
next();
}, 300);
});
srv.listen(function(){
var socket = client(srv);
socket.on('connect', function(){
expect(authenticated).to.be(true);
done();
});
});
});
it('should be ignored if socket gets closed', function(done){
var srv = http();
var sio = io(srv);
@@ -2239,6 +2332,36 @@ describe('socket.io', function(){
});
});
});
it('should disable the merge of handshake packets', function(done){
var srv = http();
var sio = io();
sio.use(function(socket, next){
next();
});
sio.listen(srv);
var socket = client(srv);
socket.on('connect', function(){
done();
});
});
it('should work with a custom namespace', (done) => {
var srv = http();
var sio = io();
sio.listen(srv);
sio.of('/chat').use(function(socket, next){
next();
});
var count = 0;
client(srv, '/').on('connect', () => {
if (++count === 2) done();
});
client(srv, '/chat').on('connect', () => {
if (++count === 2) done();
});
});
});
describe('socket middleware', function(done){