Compare commits

...

19 Commits
4.5.1 ... 4.5.4

Author SHA1 Message Date
Damien Arrachequesne
3b7ced7af7 chore(release): 4.5.4
Diff: https://github.com/socketio/socket.io/compare/4.5.3...4.5.4
2022-11-22 22:45:13 +01:00
Damien Arrachequesne
c00bb9564c chore: bump engine.io to version 6.2.1
In order to fix CVE-2022-41940.

See also: https://github.com/socketio/engine.io/security/advisories/GHSA-r7qp-cfhv-p84w
2022-11-22 22:35:53 +01:00
Damien Arrachequesne
57e5f25e26 chore: bump socket.io-parser to version 4.2.1
In order to fix CVE-2022-2421.

See also: https://github.com/advisories/GHSA-qm95-pgcg-qqfq
2022-11-22 22:32:09 +01:00
Damien Arrachequesne
f4b698418a docs: add missing versions in the changelog 2022-11-02 08:40:26 +01:00
Damien Arrachequesne
945c84be47 chore(release): 4.5.3
Diff: https://github.com/socketio/socket.io/compare/4.5.2...4.5.3
2022-10-15 07:14:45 +02:00
Damien Arrachequesne
d3d0a2d5be fix(typings): accept an HTTP2 server in the constructor
Related:

- https://github.com/socketio/socket.io/issues/4434
- https://github.com/socketio/socket.io/issues/4494
2022-10-14 11:24:36 +02:00
Damien Arrachequesne
19b225b0c8 docs(examples): update dependencies of the basic CRUD example
Related: https://github.com/socketio/socket.io/issues/4409
2022-10-14 10:39:40 +02:00
Damien Arrachequesne
8fae95dd18 docs: add jsdoc for each public method 2022-10-14 10:30:08 +02:00
Damien Arrachequesne
e6f6b906db docs: add deprecation notice for the allSockets() method 2022-10-13 15:02:23 +02:00
Damien Arrachequesne
596eb88af7 ci: upgrade to actions/checkout@3 and actions/setup-node@3
Reference: https://github.blog/changelog/2022-09-22-github-actions-all-actions-will-begin-running-on-node16-instead-of-node12/
2022-10-13 14:50:09 +02:00
Damien Arrachequesne
e357daf585 fix(typings): apply types to "io.timeout(...).emit()" calls
Typed events were not applied when calling "io.timeout(...).emit()".

Related: https://github.com/socketio/socket.io-client/issues/1555#issuecomment-1277289733

Reference: https://socket.io/docs/v4/typescript/
2022-10-13 14:50:09 +02:00
Damien Arrachequesne
10fa4a2690 refactor: add list of possible disconnection reasons
Note: some disconnection reasons could be merged in the next major
release, i.e. the Deno impl does not have "forced server close" and
"server shutting down"

Related: https://github.com/socketio/socket.io/issues/4387
2022-09-13 08:25:13 +02:00
Damien Arrachequesne
8be95b3bd3 chore(release): 4.5.2
Diff: https://github.com/socketio/socket.io/compare/4.5.1...4.5.2
2022-09-02 23:46:14 +01:00
Damien Arrachequesne
ba497ee3eb fix(uws): prevent the server from crashing after upgrade
This should fix a rare case where the Engine.IO connection was upgraded
to WebSocket while the Socket.IO socket was disconnected, which would
result in the following exception:

> TypeError: Cannot read properties of undefined (reading 'forEach')
>    at subscribe (/node_modules/socket.io/dist/uws.js:87:11)
>    at Socket.<anonymous> (/node_modules/socket.io/dist/uws.js:28:17)
>    at Socket.emit (node:events:402:35)
>    at WebSocket.onPacket (/node_modules/engine.io/build/socket.js:214:22)
>    at WebSocket.emit (node:events:390:28)
>    at WebSocket.onPacket (/node_modules/engine.io/build/transport.js:92:14)
>    at WebSocket.onData (/node_modules/engine.io/build/transport.js:101:14)
>    at message (/node_modules/engine.io/build/userver.js:56:30)

Related: https://github.com/socketio/socket.io/issues/4443
2022-09-02 23:42:26 +01:00
Alex
28038715cb ci: add explicit permissions to workflow (#4466)
Reference: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#permissions
2022-09-02 23:10:19 +01:00
Daniel Rosenwasser
134226e96c refactor: add missing constraints (#4431)
See also: https://github.com/microsoft/TypeScript/issues/49489
2022-09-01 21:13:55 +01:00
Damien Arrachequesne
9890b036cf chore: bump dependencies
Production:

- socket.io-parser: ~4.0.4 => ~4.2.0

Development:

- superagent: ^6.1.0 => ^8.0.0
- tsd: ^0.17.0 => ^0.21.0

Related: https://github.com/socketio/socket.io/issues/3709
2022-06-27 09:16:08 +02:00
Damien Arrachequesne
713a6b451b chore: bump mocha to version 10.0.0
Related: https://github.com/socketio/socket.io/issues/3710
2022-06-27 09:00:31 +02:00
Damien Arrachequesne
18f3fdab12 fix: prevent the socket from joining a room after disconnection
Calling `socket.join()` after disconnection would lead to a memory
leak, because the room was never removed from the memory:

```js
io.on("connection", (socket) => {
  socket.disconnect();
  socket.join("room1"); // leak
});
```

Related:

- https://github.com/socketio/socket.io/issues/4067
- https://github.com/socketio/socket.io/issues/4380
2022-05-25 23:18:42 +02:00
34 changed files with 7580 additions and 6034 deletions

View File

@@ -6,21 +6,31 @@ on:
schedule:
- cron: '0 0 * * 0'
permissions:
contents: read
jobs:
test-node:
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
node-version: [12, 14, 16]
steps:
- uses: actions/checkout@v2
- name: Checkout repository
uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm test
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
env:
CI: true

View File

@@ -1,3 +1,103 @@
# History
## 2022
- [4.5.4](#454-2022-11-22) (Nov 2022)
- [4.5.3](#453-2022-10-15) (Oct 2022)
- [4.5.2](#452-2022-09-02) (Sep 2022)
- [2.5.0](#250-2022-06-26) (Jun 2022) (from the [2.x](https://github.com/socketio/socket.io/tree/2.x) branch)
- [4.5.1](#451-2022-05-17) (May 2022)
- [4.5.0](#450-2022-04-23) (Apr 2022)
- [4.4.1](#441-2022-01-06) (Jan 2022)
## 2021
- [4.4.0](#440-2021-11-18) (Nov 2021)
- [4.3.2](#432-2021-11-08) (Nov 2021)
- [4.3.1](#431-2021-10-16) (Oct 2021)
- [4.3.0](#430-2021-10-14) (Oct 2021)
- [4.2.0](#420-2021-08-30) (Aug 2021)
- [4.1.3](#413-2021-07-10) (Jul 2021)
- [4.1.2](#412-2021-05-17) (May 2021)
- [4.1.1](#411-2021-05-11) (May 2021)
- [4.1.0](#410-2021-05-11) (May 2021)
- [4.0.2](#402-2021-05-06) (May 2021)
- [4.0.1](#401-2021-03-31) (Mar 2021)
- [**4.0.0**](#400-2021-03-10) (Mar 2021)
- [3.1.2](#312-2021-02-26) (Feb 2021)
- [3.1.1](#311-2021-02-03) (Feb 2021)
- [3.1.0](#310-2021-01-15) (Jan 2021)
- [2.4.1](#241-2021-01-07) (Jan 2021) (from the [2.x](https://github.com/socketio/socket.io/tree/2.x) branch)
- [3.0.5](#305-2021-01-05) (Jan 2021)
- [2.4.0](#240-2021-01-04) (Jan 2021) (from the [2.x](https://github.com/socketio/socket.io/tree/2.x) branch)
## 2020
- [3.0.4](#304-2020-12-07) (Dec 2020)
- [3.0.3](#303-2020-11-19) (Nov 2020)
- [3.0.2](#302-2020-11-17) (Nov 2020)
- [3.0.1](#301-2020-11-09) (Nov 2020)
- [**3.0.0**](#300-2020-11-05) (Nov 2020)
## 2019
- [2.3.0](#230-2019-09-20) (Sep 2019)
## 2018
- [2.2.0](#220-2018-11-29) (Nov 2018)
- [2.1.1](#211-2018-05-17) (May 2018)
- [2.1.0](#210-2018-03-29) (Mar 2018)
# Release notes
## [4.5.4](https://github.com/socketio/socket.io/compare/4.5.3...4.5.4) (2022-11-22)
This release contains a bump of:
- `engine.io` in order to fix [CVE-2022-41940](https://github.com/socketio/engine.io/security/advisories/GHSA-r7qp-cfhv-p84w)
- `socket.io-parser` in order to fix [CVE-2022-2421](https://github.com/advisories/GHSA-qm95-pgcg-qqfq).
### Dependencies
- [`engine.io@~6.2.1`](https://github.com/socketio/engine.io-client/tree/6.2.1) ([diff](https://github.com/socketio/engine.io/compare/6.2.0...6.2.1))
- [`ws@~8.2.3`](https://github.com/websockets/ws/releases/tag/8.2.3)
## [4.5.3](https://github.com/socketio/socket.io/compare/4.5.2...4.5.3) (2022-10-15)
### Bug Fixes
* **typings:** accept an HTTP2 server in the constructor ([d3d0a2d](https://github.com/socketio/socket.io/commit/d3d0a2d5beaff51fd145f810bcaf6914213f8a06))
* **typings:** apply types to "io.timeout(...).emit()" calls ([e357daf](https://github.com/socketio/socket.io/commit/e357daf5858560bc84e7e50cd36f0278d6721ea1))
## [4.5.2](https://github.com/socketio/socket.io/compare/4.5.1...4.5.2) (2022-09-02)
### Bug Fixes
* prevent the socket from joining a room after disconnection ([18f3fda](https://github.com/socketio/socket.io/commit/18f3fdab12947a9fee3e9c37cfc1da97027d1473))
* **uws:** prevent the server from crashing after upgrade ([ba497ee](https://github.com/socketio/socket.io/commit/ba497ee3eb52c4abf1464380d015d8c788714364))
# [2.5.0](https://github.com/socketio/socket.io/compare/2.4.1...2.5.0) (2022-06-26)
### Bug Fixes
* fix race condition in dynamic namespaces ([05e1278](https://github.com/socketio/socket.io/commit/05e1278cfa99f3ecf3f8f0531ffe57d850e9a05b))
* ignore packet received after disconnection ([22d4bdf](https://github.com/socketio/socket.io/commit/22d4bdf00d1a03885dc0171125faddfaef730066))
* only set 'connected' to true after middleware execution ([226cc16](https://github.com/socketio/socket.io/commit/226cc16165f9fe60f16ff4d295fb91c8971cde35))
* prevent the socket from joining a room after disconnection ([f223178](https://github.com/socketio/socket.io/commit/f223178eb655a7713303b21a78f9ef9e161d6458))
## [4.5.1](https://github.com/socketio/socket.io/compare/4.5.0...4.5.1) (2022-05-17)
@@ -234,6 +334,16 @@ we only add a field in the JSON-encoded handshake data:
* allow integers as event names ([1c220dd](https://github.com/socketio/socket.io-parser/commit/1c220ddbf45ea4b44bc8dbf6f9ae245f672ba1b9))
## [2.4.1](https://github.com/socketio/socket.io/compare/2.4.0...2.4.1) (2021-01-07)
### Reverts
* fix(security): do not allow all origins by default ([a169050](https://github.com/socketio/socket.io/commit/a1690509470e9dd5559cec4e60908ca6c23e9ba0))
## [3.0.5](https://github.com/socketio/socket.io/compare/3.0.4...3.0.5) (2021-01-05)
@@ -247,6 +357,17 @@ we only add a field in the JSON-encoded handshake data:
* restore the socket middleware functionality ([bf54327](https://github.com/socketio/socket.io/commit/bf5432742158e4d5ba2722cff4a614967dffa5b9))
# [2.4.0](https://github.com/socketio/socket.io/compare/2.3.0...2.4.0) (2021-01-04)
### Bug Fixes
* **security:** do not allow all origins by default ([f78a575](https://github.com/socketio/socket.io/commit/f78a575f66ab693c3ea96ea88429ddb1a44c86c7))
* properly overwrite the query sent in the handshake ([d33a619](https://github.com/socketio/socket.io/commit/d33a619905a4905c153d4fec337c74da5b533a9e))
## [3.0.4](https://github.com/socketio/socket.io/compare/3.0.3...3.0.4) (2020-12-07)
@@ -532,3 +653,78 @@ io.of("/admin").use((socket, next) => {
This method was kept for backward-compatibility with pre-1.0 versions.
# [2.3.0](https://github.com/socketio/socket.io/compare/2.2.0...2.3.0) (2019-09-20)
This release mainly contains a bump of the `engine.io` and `ws` packages, but no additional features.
# [2.2.0](https://github.com/socketio/socket.io/compare/2.1.1...2.2.0) (2018-11-29)
### Features
- add cache-control header when serving the client source ([#2907](https://github.com/socketio/socket.io/pull/2907)) ([b00ae50](https://github.com/socketio/socket.io/commit/b00ae50be65d1bc88fa95145f1c486a6886a6b76))
### Bug fixes
- throw an error when trying to access the clients of a dynamic namespace ([#3355](https://github.com/socketio/socket.io/pull/3355)) ([a7fbd1a](https://github.com/socketio/socket.io/commit/a7fbd1ac4a47cafd832fc62e371754df924c5903))
# [2.1.1](https://github.com/socketio/socket.io/compare/2.1.0...2.1.1) (2018-05-17)
### Features
- add local flag to the socket object ([#3129](https://github.com/socketio/socket.io/pull/3219)) ([1decae3](https://github.com/socketio/socket.io/commit/1decae341c80c0417b32d3124ca30c005240b48a))
```js
socket.local.to('room101').emit(/* */);
```
# [2.1.0](https://github.com/socketio/socket.io/compare/2.1.1...2.2.0) (2018-03-29)
### Features
- add a 'binary' flag ([#3185](https://github.com/socketio/socket.io/pull/3185)) ([f48a06c](https://github.com/socketio/socket.io/commit/f48a06c040280b44f90fd225c888910544fd63b5))
```js
// by default, the object is recursively scanned to check whether it contains some binary data
// in the following example, the check is skipped in order to improve performance
socket.binary(false).emit('plain-object', object);
// it also works at the namespace level
io.binary(false).emit('plain-object', object);
```
- add support for dynamic namespaces ([#3195](https://github.com/socketio/socket.io/pull/3195)) ([c0c79f0](https://github.com/socketio/socket.io/commit/c0c79f019e7138194e438339f8192705957c8ec3))
```js
io.of(/^\/dynamic-\d+$/).on('connect', (socket) => {
// socket.nsp.name = '/dynamic-101'
});
// client-side
const client = require('socket.io-client')('/dynamic-101');
```
### Bug fixes
- properly emit 'connect' when using a custom namespace ([#3197](https://github.com/socketio/socket.io/pull/3197)) ([f4fc517](https://github.com/socketio/socket.io/commit/f4fc517e0fe25866c95b584291487b8cbdff889d))
- include the protocol in the origins check ([#3198](https://github.com/socketio/socket.io/pull/3198)) ([1f1d64b](https://github.com/socketio/socket.io/commit/1f1d64bab61a273712a199591a3f76210d8c0959))
### Important note :warning: from Engine.IO [3.2.0 release](https://github.com/socketio/engine.io/releases/tag/3.2.0)
There are two non-breaking changes that are somehow quite important:
- `ws` was reverted as the default wsEngine (https://github.com/socketio/engine.io/pull/550), as there was several blocking issues with `uws`. You can still use `uws` by running `npm install uws --save` in your project and using the `wsEngine` option:
```js
var engine = require('engine.io');
var server = engine.listen(3000, {
wsEngine: 'uws'
});
```
- `pingTimeout` now defaults to 5 seconds (instead of 60 seconds): https://github.com/socketio/engine.io/pull/551

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
/*!
* Socket.IO v4.5.1
* Socket.IO v4.5.4
* (c) 2014-2022 Guillermo Rauch
* Released under the MIT License.
*/
@@ -12,17 +12,11 @@
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
@@ -44,11 +38,14 @@
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _extends() {
_extends = Object.assign || function (target) {
_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
@@ -61,7 +58,6 @@
return target;
};
return _extends.apply(this, arguments);
}
@@ -77,22 +73,24 @@
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
@@ -111,7 +109,7 @@
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct;
_construct = Reflect.construct.bind();
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
@@ -210,9 +208,9 @@
return object;
}
function _get(target, property, receiver) {
function _get() {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
_get = Reflect.get.bind();
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
@@ -221,14 +219,14 @@
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
return desc.get.call(arguments.length < 3 ? target : receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
return _get.apply(this, arguments);
}
function _unsupportedIterableToArray(o, minLen) {
@@ -363,11 +361,6 @@
return fileReader.readAsDataURL(data);
};
/*
* base64-arraybuffer 1.0.1 <https://github.com/niklasvh/base64-arraybuffer>
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
* Released under MIT License
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.
var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
@@ -375,7 +368,6 @@
for (var i$1 = 0; i$1 < chars.length; i$1++) {
lookup$1[chars.charCodeAt(i$1)] = i$1;
}
var decode$1 = function decode(base64) {
var bufferLength = base64.length * 0.75,
len = base64.length,
@@ -667,7 +659,7 @@
return !!this.listeners(event).length;
};
var globalThis = (function () {
var globalThisShim = function () {
if (typeof self !== "undefined") {
return self;
} else if (typeof window !== "undefined") {
@@ -675,7 +667,7 @@
} else {
return Function("return this")();
}
})();
}();
function pick(obj) {
for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
@@ -695,11 +687,11 @@
var NATIVE_CLEAR_TIMEOUT = clearTimeout;
function installTimerFunctions(obj, opts) {
if (opts.useNativeTimers) {
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
} else {
obj.setTimeoutFn = setTimeout.bind(globalThis);
obj.clearTimeoutFn = clearTimeout.bind(globalThis);
obj.setTimeoutFn = setTimeout.bind(globalThisShim);
obj.clearTimeoutFn = clearTimeout.bind(globalThisShim);
}
} // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
@@ -753,7 +745,7 @@
return _this;
}
return TransportError;
return _createClass(TransportError);
}( /*#__PURE__*/_wrapNativeSuper(Error));
var Transport = /*#__PURE__*/function (_Emitter) {
@@ -998,7 +990,7 @@
var hasCORS = value;
// browser shim for xmlhttprequest module
function XMLHttpRequest$1 (opts) {
function XHR(opts) {
var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE
try {
@@ -1009,7 +1001,7 @@
if (!xdomain) {
try {
return new globalThis[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
} catch (e) {}
}
}
@@ -1017,7 +1009,7 @@
function empty() {}
var hasXHR2 = function () {
var xhr = new XMLHttpRequest$1({
var xhr = new XHR({
xdomain: false
});
return null != xhr.responseType;
@@ -1362,7 +1354,7 @@
var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
opts.xdomain = !!this.opts.xd;
opts.xscheme = !!this.opts.xs;
var xhr = this.xhr = new XMLHttpRequest$1(opts);
var xhr = this.xhr = new XHR(opts);
try {
xhr.open(this.method, this.uri, this.async);
@@ -1513,7 +1505,7 @@
// @ts-ignore
attachEvent("onunload", unloadHandler);
} else if (typeof addEventListener === "function") {
var terminationEvent = "onpagehide" in globalThis ? "pagehide" : "unload";
var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
addEventListener(terminationEvent, unloadHandler, false);
}
}
@@ -1539,7 +1531,7 @@
};
}
}();
var WebSocket = globalThis.WebSocket || globalThis.MozWebSocket;
var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
var usingBrowserWebSocket = true;
var defaultBinaryType = "arraybuffer";
@@ -1745,7 +1737,7 @@
}, {
key: "check",
value: function check() {
return !!WebSocket && !("__initialize" in WebSocket && this.name === WS.prototype.name);
return !!WebSocket;
}
}]);
@@ -1800,11 +1792,11 @@
var regx = /\/{2,9}/g,
names = path.replace(regx, "/").split("/");
if (path.substr(0, 1) == '/' || path.length === 0) {
if (path.slice(0, 1) == '/' || path.length === 0) {
names.splice(0, 1);
}
if (path.substr(path.length - 1, 1) == '/') {
if (path.slice(-1) == '/') {
names.splice(names.length - 1, 1);
}
@@ -1904,14 +1896,16 @@
// Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
// ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
// closed/reloaded)
addEventListener("beforeunload", function () {
_this.beforeunloadEventListener = function () {
if (_this.transport) {
// silently close the transport
_this.transport.removeAllListeners();
_this.transport.close();
}
}, false);
};
addEventListener("beforeunload", _this.beforeunloadEventListener, false);
}
if (_this.hostname !== "localhost") {
@@ -2459,6 +2453,7 @@
this.transport.removeAllListeners();
if (typeof removeEventListener === "function") {
removeEventListener("beforeunload", this.beforeunloadEventListener, false);
removeEventListener("offline", this.offlineEventListener, false);
} // set ready state
@@ -2501,6 +2496,8 @@
}(Emitter);
Socket$1.protocol = protocol$1;
Socket$1.protocol;
/**
* URL parser.
*
@@ -2682,8 +2679,14 @@
function _reconstructPacket(data, buffers) {
if (!data) return data;
if (data && data._placeholder) {
return buffers[data.num]; // appropriate buffer (should be natural order anyway)
if (data && data._placeholder === true) {
var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
if (isIndexValid) {
return buffers[data.num]; // appropriate buffer (should be natural order anyway)
} else {
throw new Error("illegal attachments");
}
} else if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
data[i] = _reconstructPacket(data[i], buffers);
@@ -2843,6 +2846,10 @@
var packet;
if (typeof obj === "string") {
if (this.reconstructor) {
throw new Error("got plaintext data when reconstructing a packet");
}
packet = this.decodeString(obj);
if (packet.type === PacketType.BINARY_EVENT || packet.type === PacketType.BINARY_ACK) {
@@ -3088,6 +3095,31 @@
newListener: 1,
removeListener: 1
});
/**
* A Socket is the fundamental class for interacting with the server.
*
* A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log("connected");
* });
*
* // send an event to the server
* socket.emit("foo", "bar");
*
* socket.on("foobar", () => {
* // an event was received from the server
* });
*
* // upon disconnection
* socket.on("disconnect", (reason) => {
* console.log(`disconnected due to ${reason}`);
* });
*/
var Socket = /*#__PURE__*/function (_Emitter) {
_inherits(Socket, _Emitter);
@@ -3095,8 +3127,6 @@
/**
* `Socket` constructor.
*
* @public
*/
function Socket(io, nsp, opts) {
var _this;
@@ -3104,8 +3134,31 @@
_classCallCheck(this, Socket);
_this = _super.call(this);
/**
* Whether the socket is currently connected to the server.
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.connected); // true
* });
*
* socket.on("disconnect", () => {
* console.log(socket.connected); // false
* });
*/
_this.connected = false;
/**
* Buffer for packets received before the CONNECT packet
*/
_this.receiveBuffer = [];
/**
* Buffer for packets that will be sent once the socket is connected
*/
_this.sendBuffer = [];
_this.ids = 0;
_this.acks = {};
@@ -3122,6 +3175,17 @@
}
/**
* Whether the socket is currently disconnected
*
* @example
* const socket = io();
*
* socket.on("connect", () => {
* console.log(socket.disconnected); // false
* });
*
* socket.on("disconnect", () => {
* console.log(socket.disconnected); // true
* });
*/
@@ -3144,7 +3208,21 @@
this.subs = [on(io, "open", this.onopen.bind(this)), on(io, "packet", this.onpacket.bind(this)), on(io, "error", this.onerror.bind(this)), on(io, "close", this.onclose.bind(this))];
}
/**
* Whether the Socket will try to reconnect when its Manager connects or reconnects
* Whether the Socket will try to reconnect when its Manager connects or reconnects.
*
* @example
* const socket = io();
*
* console.log(socket.active); // true
*
* socket.on("disconnect", (reason) => {
* if (reason === "io server disconnect") {
* // the disconnection was initiated by the server, you need to manually reconnect
* console.log(socket.active); // false
* }
* // else the socket will automatically try to reconnect
* console.log(socket.active); // true
* });
*/
}, {
@@ -3155,7 +3233,12 @@
/**
* "Opens" the socket.
*
* @public
* @example
* const socket = io({
* autoConnect: false
* });
*
* socket.connect();
*/
}, {
@@ -3169,7 +3252,7 @@
return this;
}
/**
* Alias for connect()
* Alias for {@link connect()}.
*/
}, {
@@ -3180,8 +3263,17 @@
/**
* Sends a `message` event.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
*
* @return self
* @public
*/
}, {
@@ -3199,15 +3291,25 @@
* Override `emit`.
* If the event is in `events`, it's emitted normally.
*
* @example
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
*
* // with an acknowledgement from the server
* socket.emit("hello", "world", (val) => {
* // ...
* });
*
* @return self
* @public
*/
}, {
key: "emit",
value: function emit(ev) {
if (RESERVED_EVENTS.hasOwnProperty(ev)) {
throw new Error('"' + ev + '" is a reserved event name');
throw new Error('"' + ev.toString() + '" is a reserved event name');
}
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
@@ -3558,10 +3660,20 @@
this.io["_destroy"](this);
}
/**
* Disconnects the socket manually.
* Disconnects the socket manually. In that case, the socket will not try to reconnect.
*
* If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
*
* @example
* const socket = io();
*
* socket.on("disconnect", (reason) => {
* // console.log(reason); prints "io client disconnect"
* });
*
* socket.disconnect();
*
* @return self
* @public
*/
}, {
@@ -3584,10 +3696,9 @@
return this;
}
/**
* Alias for disconnect()
* Alias for {@link disconnect()}.
*
* @return self
* @public
*/
}, {
@@ -3598,9 +3709,11 @@
/**
* Sets the compress flag.
*
* @example
* socket.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
* @public
*/
}, {
@@ -3613,8 +3726,10 @@
* Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
* ready to send messages.
*
* @example
* socket.volatile.emit("hello"); // the server may or may not receive it
*
* @returns self
* @public
*/
}, {
@@ -3627,16 +3742,14 @@
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the server:
*
* ```
* @example
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the server did not acknowledge the event in the given delay
* }
* });
* ```
*
* @returns self
* @public
*/
}, {
@@ -3649,8 +3762,12 @@
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @example
* socket.onAny((event, ...args) => {
* console.log(`got ${event}`);
* });
*
* @param listener
* @public
*/
}, {
@@ -3666,8 +3783,12 @@
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @example
* socket.prependAny((event, ...args) => {
* console.log(`got event ${event}`);
* });
*
* @param listener
* @public
*/
}, {
@@ -3682,8 +3803,20 @@
/**
* Removes the listener that will be fired when any event is emitted.
*
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`got event ${event}`);
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
*
* @param listener
* @public
*/
}, {
@@ -3711,8 +3844,6 @@
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*
* @public
*/
}, {
@@ -3724,17 +3855,14 @@
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
*
* @param listener
*
* <pre><code>
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.onAnyOutgoing((event, ...args) => {
* console.log(event);
* console.log(`sent event ${event}`);
* });
*
* </pre></code>
*
* @public
* @param listener
*/
}, {
@@ -3750,17 +3878,14 @@
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @param listener
*
* <pre><code>
* Note: acknowledgements sent to the server are not included.
*
* @example
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(event);
* console.log(`sent event ${event}`);
* });
*
* </pre></code>
*
* @public
* @param listener
*/
}, {
@@ -3775,22 +3900,20 @@
/**
* Removes the listener that will be fired when any event is emitted.
*
* @param listener
*
* <pre><code>
*
* const handler = (event, ...args) => {
* console.log(event);
* @example
* const catchAllListener = (event, ...args) => {
* console.log(`sent event ${event}`);
* }
*
* socket.onAnyOutgoing(handler);
* socket.onAnyOutgoing(catchAllListener);
*
* // then later
* socket.offAnyOutgoing(handler);
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* </pre></code>
* // or remove all listeners
* socket.offAnyOutgoing();
*
* @public
* @param [listener] - the catch-all listener (optional)
*/
}, {
@@ -3818,8 +3941,6 @@
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*
* @public
*/
}, {
@@ -4179,7 +4300,11 @@
}, {
key: "ondata",
value: function ondata(data) {
this.decoder.add(data);
try {
this.decoder.add(data);
} catch (e) {
this.onclose("parse error", e);
}
}
/**
* Called when parser fully decodes a packet.
@@ -4190,7 +4315,12 @@
}, {
key: "ondecoded",
value: function ondecoded(packet) {
this.emitReserved("packet", packet);
var _this3 = this;
// the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
nextTick(function () {
_this3.emitReserved("packet", packet);
}, this.setTimeoutFn);
}
/**
* Called upon socket error.
@@ -4328,7 +4458,7 @@
}, {
key: "reconnect",
value: function reconnect() {
var _this3 = this;
var _this4 = this;
if (this._reconnecting || this.skipReconnect) return this;
var self = this;
@@ -4343,7 +4473,7 @@
var timer = this.setTimeoutFn(function () {
if (self.skipReconnect) return;
_this3.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events
_this4.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events
if (self.skipReconnect) return;
@@ -4352,7 +4482,7 @@
self._reconnecting = false;
self.reconnect();
_this3.emitReserved("reconnect_error", err);
_this4.emitReserved("reconnect_error", err);
} else {
self.onreconnect();
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -24,14 +24,14 @@
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/mocha": "^8.2.3",
"@types/chai": "^4.2.16",
"@types/mocha": "^10.0.0",
"@types/uuid": "^8.3.0",
"chai": "^4.3.4",
"mocha": "^8.3.2",
"mocha": "^10.0.0",
"nyc": "^15.1.0",
"socket.io-client": "^4.0.1",
"ts-node": "^9.1.1",
"ts-node": "^10.9.1",
"typescript": "^4.2.4"
}
}

View File

@@ -22,18 +22,27 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
/**
* Targets a room when emitting.
*
* @param room
* @return a new BroadcastOperator instance
* @public
* @example
* // the “foo” event will be broadcast to all connected clients in the “room-101” room
* io.to("room-101").emit("foo", "bar");
*
* // with an array of rooms (a client will be notified at most once)
* io.to(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* io.to("room-101").to("room-102").emit("foo", "bar");
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
public to(room: Room | Room[]) {
const rooms = new Set(this.rooms);
if (Array.isArray(room)) {
room.forEach((r) => rooms.add(r));
} else {
rooms.add(room);
}
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
rooms,
this.exceptRooms,
@@ -42,33 +51,43 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
}
/**
* Targets a room when emitting.
* Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
*
* @param room
* @return a new BroadcastOperator instance
* @public
* @example
* // disconnect all clients in the "room-101" room
* io.in("room-101").disconnectSockets();
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
public in(room: Room | Room[]) {
return this.to(room);
}
/**
* Excludes a room when emitting.
*
* @param room
* @return a new BroadcastOperator instance
* @public
* @example
* // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
* io.except("room-101").emit("foo", "bar");
*
* // with an array of rooms
* io.except(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* io.except("room-101").except("room-102").emit("foo", "bar");
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public except(
room: Room | Room[]
): BroadcastOperator<EmitEvents, SocketData> {
public except(room: Room | Room[]) {
const exceptRooms = new Set(this.exceptRooms);
if (Array.isArray(room)) {
room.forEach((r) => exceptRooms.add(r));
} else {
exceptRooms.add(room);
}
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
this.rooms,
exceptRooms,
@@ -79,15 +98,15 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
/**
* Sets the compress flag.
*
* @example
* io.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return a new BroadcastOperator instance
* @public
*/
public compress(
compress: boolean
): BroadcastOperator<EmitEvents, SocketData> {
public compress(compress: boolean) {
const flags = Object.assign({}, this.flags, { compress });
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
this.rooms,
this.exceptRooms,
@@ -100,12 +119,14 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
* 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).
*
* @example
* io.volatile.emit("hello"); // the clients may or may not receive it
*
* @return a new BroadcastOperator instance
* @public
*/
public get volatile(): BroadcastOperator<EmitEvents, SocketData> {
public get volatile() {
const flags = Object.assign({}, this.flags, { volatile: true });
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
this.rooms,
this.exceptRooms,
@@ -116,12 +137,15 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
/**
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
*
* @return a new BroadcastOperator instance
* @public
* @example
* // the “foo” event will be broadcast to all connected clients on this node
* io.local.emit("foo", "bar");
*
* @return a new {@link BroadcastOperator} instance for chaining
*/
public get local(): BroadcastOperator<EmitEvents, SocketData> {
public get local() {
const flags = Object.assign({}, this.flags, { local: true });
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
this.rooms,
this.exceptRooms,
@@ -132,19 +156,20 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
/**
* Adds a timeout in milliseconds for the next operation
*
* <pre><code>
*
* @example
* io.timeout(1000).emit("some-event", (err, responses) => {
* // ...
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* </pre></code>
*
* @param timeout
*/
public timeout(timeout: number) {
const flags = Object.assign({}, this.flags, { timeout });
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
this.rooms,
this.exceptRooms,
@@ -155,15 +180,30 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
/**
* Emits to all clients.
*
* @example
* // the “foo” event will be broadcast to all connected clients
* io.emit("foo", "bar");
*
* // the “foo” event will be broadcast to all connected clients in the “room-101” room
* io.to("room-101").emit("foo", "bar");
*
* // with an acknowledgement expected from all connected clients
* io.timeout(1000).emit("some-event", (err, responses) => {
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* @return Always true
* @public
*/
public emit<Ev extends EventNames<EmitEvents>>(
ev: Ev,
...args: EventParams<EmitEvents, Ev>
): boolean {
if (RESERVED_EVENTS.has(ev)) {
throw new Error(`"${ev}" is a reserved event name`);
throw new Error(`"${String(ev)}" is a reserved event name`);
}
// set up packet object
const data = [ev, ...args];
@@ -239,7 +279,8 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
/**
* Gets a list of clients.
*
* @public
* @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or
* {@link fetchSockets} instead.
*/
public allSockets(): Promise<Set<SocketId>> {
if (!this.adapter) {
@@ -251,13 +292,30 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
}
/**
* Returns the matching socket instances
* Returns the matching socket instances. This method works across a cluster of several Socket.IO servers.
*
* @public
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* // return all Socket instances
* const sockets = await io.fetchSockets();
*
* // return all Socket instances in the "room1" room
* const sockets = await io.in("room1").fetchSockets();
*
* for (const socket of sockets) {
* console.log(socket.id);
* console.log(socket.handshake);
* console.log(socket.rooms);
* console.log(socket.data);
*
* socket.emit("hello");
* socket.join("room1");
* socket.leave("room2");
* socket.disconnect();
* }
*/
public fetchSockets<SocketData = any>(): Promise<
RemoteSocket<EmitEvents, SocketData>[]
> {
public fetchSockets(): Promise<RemoteSocket<EmitEvents, SocketData>[]> {
return this.adapter
.fetchSockets({
rooms: this.rooms,
@@ -280,10 +338,19 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
}
/**
* Makes the matching socket instances join the specified rooms
* Makes the matching socket instances join the specified rooms.
*
* @param room
* @public
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
*
* // make all socket instances join the "room1" room
* io.socketsJoin("room1");
*
* // make all socket instances in the "room1" room join the "room2" and "room3" rooms
* io.in("room1").socketsJoin(["room2", "room3"]);
*
* @param room - a room, or an array of rooms
*/
public socketsJoin(room: Room | Room[]): void {
this.adapter.addSockets(
@@ -297,10 +364,18 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
}
/**
* Makes the matching socket instances leave the specified rooms
* Makes the matching socket instances leave the specified rooms.
*
* @param room
* @public
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* // make all socket instances leave the "room1" room
* io.socketsLeave("room1");
*
* // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
* io.in("room1").socketsLeave(["room2", "room3"]);
*
* @param room - a room, or an array of rooms
*/
public socketsLeave(room: Room | Room[]): void {
this.adapter.delSockets(
@@ -314,10 +389,18 @@ export class BroadcastOperator<EmitEvents extends EventsMap, SocketData>
}
/**
* Makes the matching socket instances disconnect
* Makes the matching socket instances disconnect.
*
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* // make all socket instances disconnect (the connections might be kept alive for other namespaces)
* io.disconnectSockets();
*
* // make all socket instances in the "room1" room disconnect and close the underlying connections
* io.in("room1").disconnectSockets(true);
*
* @param close - whether to close the underlying connection
* @public
*/
public disconnectSockets(close: boolean = false): void {
this.adapter.disconnectSockets(
@@ -359,7 +442,10 @@ export class RemoteSocket<EmitEvents extends EventsMap, SocketData>
this.handshake = details.handshake;
this.rooms = new Set(details.rooms);
this.data = details.data;
this.operator = new BroadcastOperator(adapter, new Set([this.id]));
this.operator = new BroadcastOperator<EmitEvents, SocketData>(
adapter,
new Set([this.id])
);
}
public emit<Ev extends EventNames<EmitEvents>>(
@@ -373,7 +459,6 @@ export class RemoteSocket<EmitEvents extends EventsMap, SocketData>
* Joins a room.
*
* @param {String|Array} room - room or array of rooms
* @public
*/
public join(room: Room | Room[]): void {
return this.operator.socketsJoin(room);
@@ -383,7 +468,6 @@ export class RemoteSocket<EmitEvents extends EventsMap, SocketData>
* Leaves a room.
*
* @param {String} room
* @public
*/
public leave(room: Room): void {
return this.operator.socketsLeave(room);
@@ -394,8 +478,6 @@ export class RemoteSocket<EmitEvents extends EventsMap, SocketData>
*
* @param {Boolean} close - if `true`, closes the underlying connection
* @return {Socket} self
*
* @public
*/
public disconnect(close = false): this {
this.operator.disconnectSockets(close);

View File

@@ -18,6 +18,13 @@ interface WriteOptions {
wsPreEncoded?: string;
}
type CloseReason =
| "transport error"
| "transport close"
| "forced close"
| "ping timeout"
| "parse error";
export class Client<
ListenEvents extends EventsMap,
EmitEvents extends EventsMap,
@@ -306,7 +313,7 @@ export class Client<
* @param reason
* @private
*/
private onclose(reason: string): void {
private onclose(reason: CloseReason | "forced server close"): void {
debug("client close with reason %s", reason);
// ignore a potential subsequent `close` event

View File

@@ -1,5 +1,6 @@
import http = require("http");
import type { Server as HTTPSServer } from "https";
import type { Http2SecureServer } from "http2";
import { createReadStream } from "fs";
import { createDeflate, createGzip, createBrotliCompress } from "zlib";
import accepts = require("accepts");
@@ -72,6 +73,32 @@ interface ServerOptions extends EngineOptions, AttachOptions {
connectTimeout: number;
}
/**
* Represents a Socket.IO server.
*
* @example
* import { Server } from "socket.io";
*
* const io = new Server();
*
* io.on("connection", (socket) => {
* console.log(`socket ${socket.id} connected`);
*
* // send an event to the client
* socket.emit("foo", "bar");
*
* socket.on("foobar", () => {
* // an event was received from the client
* });
*
* // upon disconnection
* socket.on("disconnect", (reason) => {
* console.log(`socket ${socket.id} disconnected due to ${reason}`);
* });
* });
*
* io.listen(3000);
*/
export class Server<
ListenEvents extends EventsMap = DefaultEventsMap,
EmitEvents extends EventsMap = ListenEvents,
@@ -96,11 +123,8 @@ export class Server<
/**
* A reference to the underlying Engine.IO server.
*
* Example:
*
* <code>
* const clientsCount = io.engine.clientsCount;
* </code>
* @example
* const clientsCount = io.engine.clientsCount;
*
*/
public engine: any;
@@ -132,18 +156,17 @@ export class Server<
* @private
*/
_connectTimeout: number;
private httpServer: http.Server | HTTPSServer;
private httpServer: http.Server | HTTPSServer | Http2SecureServer;
/**
* Server constructor.
*
* @param srv http server, port, or options
* @param [opts]
* @public
*/
constructor(opts?: Partial<ServerOptions>);
constructor(
srv?: http.Server | HTTPSServer | number,
srv?: http.Server | HTTPSServer | Http2SecureServer | number,
opts?: Partial<ServerOptions>
);
constructor(
@@ -152,6 +175,7 @@ export class Server<
| Partial<ServerOptions>
| http.Server
| HTTPSServer
| Http2SecureServer
| number,
opts?: Partial<ServerOptions>
);
@@ -161,6 +185,7 @@ export class Server<
| Partial<ServerOptions>
| http.Server
| HTTPSServer
| Http2SecureServer
| number,
opts: Partial<ServerOptions> = {}
) {
@@ -182,7 +207,9 @@ export class Server<
this.sockets = this.of("/");
this.opts = opts;
if (srv || typeof srv == "number")
this.attach(srv as http.Server | HTTPSServer | number);
this.attach(
srv as http.Server | HTTPSServer | Http2SecureServer | number
);
}
/**
@@ -190,7 +217,6 @@ export class Server<
*
* @param v - whether to serve client code
* @return self when setting or value when getting
* @public
*/
public serveClient(v: boolean): this;
public serveClient(): boolean;
@@ -253,7 +279,6 @@ export class Server<
*
* @param {String} v pathname
* @return {Server|String} self when setting or value when getting
* @public
*/
public path(v: string): this;
public path(): string;
@@ -275,7 +300,6 @@ export class Server<
/**
* Set the delay after which a client without namespace is closed
* @param v
* @public
*/
public connectTimeout(v: number): this;
public connectTimeout(): number;
@@ -291,7 +315,6 @@ export class Server<
*
* @param v pathname
* @return self when setting or value when getting
* @public
*/
public adapter(): AdapterConstructor | undefined;
public adapter(v: AdapterConstructor): this;
@@ -312,10 +335,9 @@ export class Server<
* @param srv - server or port
* @param opts - options passed to engine.io
* @return self
* @public
*/
public listen(
srv: http.Server | HTTPSServer | number,
srv: http.Server | HTTPSServer | Http2SecureServer | number,
opts: Partial<ServerOptions> = {}
): this {
return this.attach(srv, opts);
@@ -327,10 +349,9 @@ export class Server<
* @param srv - server or port
* @param opts - options passed to engine.io
* @return self
* @public
*/
public attach(
srv: http.Server | HTTPSServer | number,
srv: http.Server | HTTPSServer | Http2SecureServer | number,
opts: Partial<ServerOptions> = {}
): this {
if ("function" == typeof srv) {
@@ -436,7 +457,7 @@ export class Server<
* @private
*/
private initEngine(
srv: http.Server | HTTPSServer,
srv: http.Server | HTTPSServer | Http2SecureServer,
opts: EngineOptions & AttachOptions
): void {
// initialize engine
@@ -459,7 +480,9 @@ export class Server<
* @param srv http server
* @private
*/
private attachServe(srv: http.Server | HTTPSServer): void {
private attachServe(
srv: http.Server | HTTPSServer | Http2SecureServer
): void {
debug("attaching client serving req handler");
const evs = srv.listeners("request").slice(0);
@@ -561,7 +584,6 @@ export class Server<
*
* @param {engine.Server} engine engine.io (or compatible) server
* @return self
* @public
*/
public bind(engine): this {
this.engine = engine;
@@ -589,9 +611,20 @@ export class Server<
/**
* Looks up a namespace.
*
* @param {String|RegExp|Function} name nsp name
* @example
* // with a simple string
* const myNamespace = io.of("/my-namespace");
*
* // with a regex
* const dynamicNsp = io.of(/^\/dynamic-\d+$/).on("connection", (socket) => {
* const namespace = socket.nsp; // newNamespace.name === "/dynamic-101"
*
* // broadcast to all clients in the given sub-namespace
* namespace.emit("hello");
* });
*
* @param name - nsp name
* @param fn optional, nsp `connection` ev handler
* @public
*/
public of(
name: string | RegExp | ParentNspNameMatchFn,
@@ -637,7 +670,6 @@ export class Server<
* Closes server connection
*
* @param [fn] optional, called as `fn([err])` on error OR all conns closed
* @public
*/
public close(fn?: (err?: Error) => void): void {
for (const socket of this.sockets.sockets.values()) {
@@ -657,10 +689,15 @@ export class Server<
}
/**
* Sets up namespace middleware.
* Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
*
* @return self
* @public
* @example
* io.use((socket, next) => {
* // ...
* next();
* });
*
* @param fn - the middleware function
*/
public use(
fn: (
@@ -675,43 +712,71 @@ export class Server<
/**
* Targets a room when emitting.
*
* @param room
* @return self
* @public
* @example
* // the “foo” event will be broadcast to all connected clients in the “room-101” room
* io.to("room-101").emit("foo", "bar");
*
* // with an array of rooms (a client will be notified at most once)
* io.to(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* io.to("room-101").to("room-102").emit("foo", "bar");
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
public to(room: Room | Room[]) {
return this.sockets.to(room);
}
/**
* Targets a room when emitting.
* Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
*
* @param room
* @return self
* @public
* @example
* // disconnect all clients in the "room-101" room
* io.in("room-101").disconnectSockets();
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
public in(room: Room | Room[]) {
return this.sockets.in(room);
}
/**
* Excludes a room when emitting.
*
* @param name
* @return self
* @public
* @example
* // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
* io.except("room-101").emit("foo", "bar");
*
* // with an array of rooms
* io.except(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* io.except("room-101").except("room-102").emit("foo", "bar");
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public except(
name: Room | Room[]
): BroadcastOperator<EmitEvents, SocketData> {
return this.sockets.except(name);
public except(room: Room | Room[]) {
return this.sockets.except(room);
}
/**
* Sends a `message` event to all clients.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* io.send("hello");
*
* // this is equivalent to
* io.emit("message", "hello");
*
* @return self
* @public
*/
public send(...args: EventParams<EmitEvents, "message">): this {
this.sockets.emit("message", ...args);
@@ -719,10 +784,9 @@ export class Server<
}
/**
* Sends a `message` event to all clients.
* Sends a `message` event to all clients. Alias of {@link send}.
*
* @return self
* @public
*/
public write(...args: EventParams<EmitEvents, "message">): this {
this.sockets.emit("message", ...args);
@@ -730,11 +794,30 @@ export class Server<
}
/**
* Emit a packet to other Socket.IO servers
* Sends a message to the other Socket.IO servers of the cluster.
*
* @example
* io.serverSideEmit("hello", "world");
*
* io.on("hello", (arg1) => {
* console.log(arg1); // prints "world"
* });
*
* // acknowledgements (without binary content) are supported too:
* io.serverSideEmit("ping", (err, responses) => {
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* io.on("ping", (cb) => {
* cb("pong");
* });
*
* @param ev - the event name
* @param args - an array of arguments, which may include an acknowledgement callback at the end
* @public
*/
public serverSideEmit<Ev extends EventNames<ServerSideEvents>>(
ev: Ev,
@@ -746,7 +829,8 @@ export class Server<
/**
* Gets a list of socket ids.
*
* @public
* @deprecated this method will be removed in the next major release, please use {@link Server#serverSideEmit} or
* {@link Server#fetchSockets} instead.
*/
public allSockets(): Promise<Set<SocketId>> {
return this.sockets.allSockets();
@@ -755,13 +839,13 @@ export class Server<
/**
* Sets the compress flag.
*
* @example
* io.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
* @public
* @return a new {@link BroadcastOperator} instance for chaining
*/
public compress(
compress: boolean
): BroadcastOperator<EmitEvents, SocketData> {
public compress(compress: boolean) {
return this.sockets.compress(compress);
}
@@ -770,34 +854,40 @@ export class Server<
* 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).
*
* @return self
* @public
* @example
* io.volatile.emit("hello"); // the clients may or may not receive it
*
* @return a new {@link BroadcastOperator} instance for chaining
*/
public get volatile(): BroadcastOperator<EmitEvents, SocketData> {
public get volatile() {
return this.sockets.volatile;
}
/**
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
*
* @return self
* @public
* @example
* // the “foo” event will be broadcast to all connected clients on this node
* io.local.emit("foo", "bar");
*
* @return a new {@link BroadcastOperator} instance for chaining
*/
public get local(): BroadcastOperator<EmitEvents, SocketData> {
public get local() {
return this.sockets.local;
}
/**
* Adds a timeout in milliseconds for the next operation
*
* <pre><code>
* Adds a timeout in milliseconds for the next operation.
*
* @example
* io.timeout(1000).emit("some-event", (err, responses) => {
* // ...
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* </pre></code>
*
* @param timeout
*/
public timeout(timeout: number) {
@@ -805,41 +895,85 @@ export class Server<
}
/**
* Returns the matching socket instances
* Returns the matching socket instances.
*
* @public
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* // return all Socket instances
* const sockets = await io.fetchSockets();
*
* // return all Socket instances in the "room1" room
* const sockets = await io.in("room1").fetchSockets();
*
* for (const socket of sockets) {
* console.log(socket.id);
* console.log(socket.handshake);
* console.log(socket.rooms);
* console.log(socket.data);
*
* socket.emit("hello");
* socket.join("room1");
* socket.leave("room2");
* socket.disconnect();
* }
*/
public fetchSockets(): Promise<RemoteSocket<EmitEvents, SocketData>[]> {
return this.sockets.fetchSockets();
}
/**
* Makes the matching socket instances join the specified rooms
* Makes the matching socket instances join the specified rooms.
*
* @param room
* @public
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
*
* // make all socket instances join the "room1" room
* io.socketsJoin("room1");
*
* // make all socket instances in the "room1" room join the "room2" and "room3" rooms
* io.in("room1").socketsJoin(["room2", "room3"]);
*
* @param room - a room, or an array of rooms
*/
public socketsJoin(room: Room | Room[]): void {
public socketsJoin(room: Room | Room[]) {
return this.sockets.socketsJoin(room);
}
/**
* Makes the matching socket instances leave the specified rooms
* Makes the matching socket instances leave the specified rooms.
*
* @param room
* @public
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* // make all socket instances leave the "room1" room
* io.socketsLeave("room1");
*
* // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
* io.in("room1").socketsLeave(["room2", "room3"]);
*
* @param room - a room, or an array of rooms
*/
public socketsLeave(room: Room | Room[]): void {
public socketsLeave(room: Room | Room[]) {
return this.sockets.socketsLeave(room);
}
/**
* Makes the matching socket instances disconnect
* Makes the matching socket instances disconnect.
*
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* // make all socket instances disconnect (the connections might be kept alive for other namespaces)
* io.disconnectSockets();
*
* // make all socket instances in the "room1" room disconnect and close the underlying connections
* io.in("room1").disconnectSockets(true);
*
* @param close - whether to close the underlying connection
* @public
*/
public disconnectSockets(close: boolean = false): void {
public disconnectSockets(close: boolean = false) {
return this.sockets.disconnectSockets(close);
}
}

View File

@@ -33,9 +33,9 @@ export interface NamespaceReservedEventsMap<
}
export interface ServerReservedEventsMap<
ListenEvents,
EmitEvents,
ServerSideEvents,
ListenEvents extends EventsMap,
EmitEvents extends EventsMap,
ServerSideEvents extends EventsMap,
SocketData
> extends NamespaceReservedEventsMap<
ListenEvents,
@@ -52,6 +52,59 @@ export const RESERVED_EVENTS: ReadonlySet<string | Symbol> = new Set<
keyof ServerReservedEventsMap<never, never, never, never>
>(<const>["connect", "connection", "new_namespace"]);
/**
* A Namespace is a communication channel that allows you to split the logic of your application over a single shared
* connection.
*
* Each namespace has its own:
*
* - event handlers
*
* ```
* io.of("/orders").on("connection", (socket) => {
* socket.on("order:list", () => {});
* socket.on("order:create", () => {});
* });
*
* io.of("/users").on("connection", (socket) => {
* socket.on("user:list", () => {});
* });
* ```
*
* - rooms
*
* ```
* const orderNamespace = io.of("/orders");
*
* orderNamespace.on("connection", (socket) => {
* socket.join("room1");
* orderNamespace.to("room1").emit("hello");
* });
*
* const userNamespace = io.of("/users");
*
* userNamespace.on("connection", (socket) => {
* socket.join("room1"); // distinct from the room in the "orders" namespace
* userNamespace.to("room1").emit("holà");
* });
* ```
*
* - middlewares
*
* ```
* const orderNamespace = io.of("/orders");
*
* orderNamespace.use((socket, next) => {
* // ensure the socket has access to the "orders" namespace
* });
*
* const userNamespace = io.of("/users");
*
* userNamespace.use((socket, next) => {
* // ensure the socket has access to the "users" namespace
* });
* ```
*/
export class Namespace<
ListenEvents extends EventsMap = DefaultEventsMap,
EmitEvents extends EventsMap = ListenEvents,
@@ -123,10 +176,17 @@ export class Namespace<
}
/**
* Sets up namespace middleware.
* Registers a middleware, which is a function that gets executed for every incoming {@link Socket}.
*
* @return self
* @public
* @example
* const myNamespace = io.of("/my-namespace");
*
* myNamespace.use((socket, next) => {
* // ...
* next();
* });
*
* @param fn - the middleware function
*/
public use(
fn: (
@@ -171,36 +231,63 @@ export class Namespace<
/**
* Targets a room when emitting.
*
* @param room
* @return self
* @public
* @example
* const myNamespace = io.of("/my-namespace");
*
* // the “foo” event will be broadcast to all connected clients in the “room-101” room
* myNamespace.to("room-101").emit("foo", "bar");
*
* // with an array of rooms (a client will be notified at most once)
* myNamespace.to(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* myNamespace.to("room-101").to("room-102").emit("foo", "bar");
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
return new BroadcastOperator(this.adapter).to(room);
public to(room: Room | Room[]) {
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).to(room);
}
/**
* Targets a room when emitting.
* Targets a room when emitting. Similar to `to()`, but might feel clearer in some cases:
*
* @param room
* @return self
* @public
* @example
* const myNamespace = io.of("/my-namespace");
*
* // disconnect all clients in the "room-101" room
* myNamespace.in("room-101").disconnectSockets();
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
return new BroadcastOperator(this.adapter).in(room);
public in(room: Room | Room[]) {
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).in(room);
}
/**
* Excludes a room when emitting.
*
* @param room
* @return self
* @public
* @example
* const myNamespace = io.of("/my-namespace");
*
* // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
* myNamespace.except("room-101").emit("foo", "bar");
*
* // with an array of rooms
* myNamespace.except(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* myNamespace.except("room-101").except("room-102").emit("foo", "bar");
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public except(
room: Room | Room[]
): BroadcastOperator<EmitEvents, SocketData> {
return new BroadcastOperator(this.adapter).except(room);
public except(room: Room | Room[]) {
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).except(
room
);
}
/**
@@ -218,34 +305,38 @@ export class Namespace<
const socket = new Socket(this, client, query);
this.run(socket, (err) => {
process.nextTick(() => {
if ("open" == client.conn.readyState) {
if (err) {
if (client.conn.protocol === 3) {
return socket._error(err.data || err.message);
} else {
return socket._error({
message: err.message,
data: err.data,
});
}
}
// track socket
this.sockets.set(socket.id, socket);
// it's paramount that the internal `onconnect` logic
// fires before user-set events to prevent state order
// violations (such as a disconnection before the connection
// logic is complete)
socket._onconnect();
if (fn) fn();
// fire user-set events
this.emitReserved("connect", socket);
this.emitReserved("connection", socket);
} else {
if ("open" !== client.conn.readyState) {
debug("next called after client was closed - ignoring socket");
socket._cleanup();
return;
}
if (err) {
debug("middleware error, sending CONNECT_ERROR packet to the client");
socket._cleanup();
if (client.conn.protocol === 3) {
return socket._error(err.data || err.message);
} else {
return socket._error({
message: err.message,
data: err.data,
});
}
}
// track socket
this.sockets.set(socket.id, socket);
// it's paramount that the internal `onconnect` logic
// fires before user-set events to prevent state order
// violations (such as a disconnection before the connection
// logic is complete)
socket._onconnect();
if (fn) fn();
// fire user-set events
this.emitReserved("connect", socket);
this.emitReserved("connection", socket);
});
});
return socket;
@@ -267,10 +358,26 @@ export class Namespace<
}
/**
* Emits to all clients.
* Emits to all connected clients.
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* myNamespace.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* myNamespace.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
*
* // with an acknowledgement from the clients
* myNamespace.timeout(1000).emit("some-event", (err, responses) => {
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* @return Always true
* @public
*/
public emit<Ev extends EventNames<EmitEvents>>(
ev: Ev,
@@ -285,8 +392,19 @@ export class Namespace<
/**
* Sends a `message` event to all clients.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* myNamespace.send("hello");
*
* // this is equivalent to
* myNamespace.emit("message", "hello");
*
* @return self
* @public
*/
public send(...args: EventParams<EmitEvents, "message">): this {
this.emit("message", ...args);
@@ -294,10 +412,9 @@ export class Namespace<
}
/**
* Sends a `message` event to all clients.
* Sends a `message` event to all clients. Sends a `message` event. Alias of {@link send}.
*
* @return self
* @public
*/
public write(...args: EventParams<EmitEvents, "message">): this {
this.emit("message", ...args);
@@ -305,18 +422,39 @@ export class Namespace<
}
/**
* Emit a packet to other Socket.IO servers
* Sends a message to the other Socket.IO servers of the cluster.
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* myNamespace.serverSideEmit("hello", "world");
*
* myNamespace.on("hello", (arg1) => {
* console.log(arg1); // prints "world"
* });
*
* // acknowledgements (without binary content) are supported too:
* myNamespace.serverSideEmit("ping", (err, responses) => {
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* myNamespace.on("ping", (cb) => {
* cb("pong");
* });
*
* @param ev - the event name
* @param args - an array of arguments, which may include an acknowledgement callback at the end
* @public
*/
public serverSideEmit<Ev extends EventNames<ServerSideEvents>>(
ev: Ev,
...args: EventParams<ServerSideEvents, Ev>
): boolean {
if (RESERVED_EVENTS.has(ev)) {
throw new Error(`"${ev}" is a reserved event name`);
throw new Error(`"${String(ev)}" is a reserved event name`);
}
args.unshift(ev);
this.adapter.serverSideEmit(args);
@@ -337,24 +475,30 @@ export class Namespace<
/**
* Gets a list of clients.
*
* @return self
* @public
* @deprecated this method will be removed in the next major release, please use {@link Namespace#serverSideEmit} or
* {@link Namespace#fetchSockets} instead.
*/
public allSockets(): Promise<Set<SocketId>> {
return new BroadcastOperator(this.adapter).allSockets();
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter
).allSockets();
}
/**
* Sets the compress flag.
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* myNamespace.compress(false).emit("hello");
*
* @param compress - if `true`, compresses the sending data
* @return self
* @public
*/
public compress(
compress: boolean
): BroadcastOperator<EmitEvents, SocketData> {
return new BroadcastOperator(this.adapter).compress(compress);
public compress(compress: boolean) {
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).compress(
compress
);
}
/**
@@ -362,76 +506,149 @@ export class Namespace<
* 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).
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* myNamespace.volatile.emit("hello"); // the clients may or may not receive it
*
* @return self
* @public
*/
public get volatile(): BroadcastOperator<EmitEvents, SocketData> {
return new BroadcastOperator(this.adapter).volatile;
public get volatile() {
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).volatile;
}
/**
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
*
* @return self
* @public
* @example
* const myNamespace = io.of("/my-namespace");
*
* // the “foo” event will be broadcast to all connected clients on this node
* myNamespace.local.emit("foo", "bar");
*
* @return a new {@link BroadcastOperator} instance for chaining
*/
public get local(): BroadcastOperator<EmitEvents, SocketData> {
return new BroadcastOperator(this.adapter).local;
public get local() {
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).local;
}
/**
* Adds a timeout in milliseconds for the next operation
* Adds a timeout in milliseconds for the next operation.
*
* <pre><code>
* @example
* const myNamespace = io.of("/my-namespace");
*
* io.timeout(1000).emit("some-event", (err, responses) => {
* // ...
* myNamespace.timeout(1000).emit("some-event", (err, responses) => {
* if (err) {
* // some clients did not acknowledge the event in the given delay
* } else {
* console.log(responses); // one response per client
* }
* });
*
* </pre></code>
*
* @param timeout
*/
public timeout(timeout: number) {
return new BroadcastOperator(this.adapter).timeout(timeout);
return new BroadcastOperator<EmitEvents, SocketData>(this.adapter).timeout(
timeout
);
}
/**
* Returns the matching socket instances
* Returns the matching socket instances.
*
* @public
*/
public fetchSockets(): Promise<RemoteSocket<EmitEvents, SocketData>[]> {
return new BroadcastOperator(this.adapter).fetchSockets();
}
/**
* Makes the matching socket instances join the specified rooms
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @param room
* @public
*/
public socketsJoin(room: Room | Room[]): void {
return new BroadcastOperator(this.adapter).socketsJoin(room);
}
/**
* Makes the matching socket instances leave the specified rooms
* @example
* const myNamespace = io.of("/my-namespace");
*
* @param room
* @public
* // return all Socket instances
* const sockets = await myNamespace.fetchSockets();
*
* // return all Socket instances in the "room1" room
* const sockets = await myNamespace.in("room1").fetchSockets();
*
* for (const socket of sockets) {
* console.log(socket.id);
* console.log(socket.handshake);
* console.log(socket.rooms);
* console.log(socket.data);
*
* socket.emit("hello");
* socket.join("room1");
* socket.leave("room2");
* socket.disconnect();
* }
*/
public socketsLeave(room: Room | Room[]): void {
return new BroadcastOperator(this.adapter).socketsLeave(room);
public fetchSockets() {
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter
).fetchSockets();
}
/**
* Makes the matching socket instances disconnect
* Makes the matching socket instances join the specified rooms.
*
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* // make all socket instances join the "room1" room
* myNamespace.socketsJoin("room1");
*
* // make all socket instances in the "room1" room join the "room2" and "room3" rooms
* myNamespace.in("room1").socketsJoin(["room2", "room3"]);
*
* @param room - a room, or an array of rooms
*/
public socketsJoin(room: Room | Room[]) {
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter
).socketsJoin(room);
}
/**
* Makes the matching socket instances leave the specified rooms.
*
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* // make all socket instances leave the "room1" room
* myNamespace.socketsLeave("room1");
*
* // make all socket instances in the "room1" room leave the "room2" and "room3" rooms
* myNamespace.in("room1").socketsLeave(["room2", "room3"]);
*
* @param room - a room, or an array of rooms
*/
public socketsLeave(room: Room | Room[]) {
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter
).socketsLeave(room);
}
/**
* Makes the matching socket instances disconnect.
*
* Note: this method also works within a cluster of multiple Socket.IO servers, with a compatible {@link Adapter}.
*
* @example
* const myNamespace = io.of("/my-namespace");
*
* // make all socket instances disconnect (the connections might be kept alive for other namespaces)
* myNamespace.disconnectSockets();
*
* // make all socket instances in the "room1" room disconnect and close the underlying connections
* myNamespace.in("room1").disconnectSockets(true);
*
* @param close - whether to close the underlying connection
* @public
*/
public disconnectSockets(close: boolean = false): void {
return new BroadcastOperator(this.adapter).disconnectSockets(close);
public disconnectSockets(close: boolean = false) {
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter
).disconnectSockets(close);
}
}

View File

@@ -25,9 +25,23 @@ const debug = debugModule("socket.io:socket");
type ClientReservedEvents = "connect_error";
// TODO for next major release: cleanup disconnect reasons
export type DisconnectReason =
// Engine.IO close reasons
| "transport error"
| "transport close"
| "forced close"
| "ping timeout"
| "parse error"
// Socket.IO disconnect reasons
| "server shutting down"
| "forced server close"
| "client namespace disconnect"
| "server namespace disconnect";
export interface SocketReservedEventsMap {
disconnect: (reason: string) => void;
disconnecting: (reason: string) => void;
disconnect: (reason: DisconnectReason) => void;
disconnecting: (reason: DisconnectReason) => void;
error: (err: Error) => void;
}
@@ -112,6 +126,39 @@ export interface Handshake {
*/
export type Event = [string, ...any[]];
function noop() {}
/**
* This is the main object for interacting with a client.
*
* A Socket belongs to a given {@link Namespace} and uses an underlying {@link Client} to communicate.
*
* Within each {@link Namespace}, you can also define arbitrary channels (called "rooms") that the {@link Socket} can
* join and leave. That provides a convenient way to broadcast to a group of socket instances.
*
* @example
* io.on("connection", (socket) => {
* console.log(`socket ${socket.id} connected`);
*
* // send an event to the client
* socket.emit("foo", "bar");
*
* socket.on("foobar", () => {
* // an event was received from the client
* });
*
* // join the room named "room1"
* socket.join("room1");
*
* // broadcast to everyone in the room named "room1"
* io.to("room1").emit("hello");
*
* // upon disconnection
* socket.on("disconnect", (reason) => {
* console.log(`socket ${socket.id} disconnected due to ${reason}`);
* });
* });
*/
export class Socket<
ListenEvents extends EventsMap = DefaultEventsMap,
EmitEvents extends EventsMap = ListenEvents,
@@ -122,13 +169,32 @@ export class Socket<
EmitEvents,
SocketReservedEventsMap
> {
/**
* An unique identifier for the session.
*/
public readonly id: SocketId;
/**
* The handshake details.
*/
public readonly handshake: Handshake;
/**
* Additional information that can be attached to the Socket instance and which will be used in the fetchSockets method
* Additional information that can be attached to the Socket instance and which will be used in the
* {@link Server.fetchSockets()} method.
*/
public data: Partial<SocketData> = {};
/**
* Whether the socket is currently connected or not.
*
* @example
* io.use((socket, next) => {
* console.log(socket.connected); // false
* next();
* });
*
* io.on("connection", (socket) => {
* console.log(socket.connected); // true
* });
*/
public connected: boolean = false;
private readonly server: Server<
@@ -193,15 +259,27 @@ export class Socket<
/**
* Emits to this client.
*
* @example
* io.on("connection", (socket) => {
* socket.emit("hello", "world");
*
* // all serializable datastructures are supported (no need to call JSON.stringify)
* socket.emit("hello", 1, "2", { 3: ["4"], 5: Buffer.from([6]) });
*
* // with an acknowledgement from the client
* socket.emit("hello", "world", (val) => {
* // ...
* });
* });
*
* @return Always returns `true`.
* @public
*/
public emit<Ev extends EventNames<EmitEvents>>(
ev: Ev,
...args: EventParams<EmitEvents, Ev>
): boolean {
if (RESERVED_EVENTS.has(ev)) {
throw new Error(`"${ev}" is a reserved event name`);
throw new Error(`"${String(ev)}" is a reserved event name`);
}
const data: any[] = [ev, ...args];
const packet: any = {
@@ -252,43 +330,83 @@ export class Socket<
/**
* Targets a room when broadcasting.
*
* @param room
* @return self
* @public
* @example
* io.on("connection", (socket) => {
* // the “foo” event will be broadcast to all connected clients in the “room-101” room, except this socket
* socket.to("room-101").emit("foo", "bar");
*
* // the code above is equivalent to:
* io.to("room-101").except(socket.id).emit("foo", "bar");
*
* // with an array of rooms (a client will be notified at most once)
* socket.to(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* socket.to("room-101").to("room-102").emit("foo", "bar");
* });
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public to(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
public to(room: Room | Room[]) {
return this.newBroadcastOperator().to(room);
}
/**
* Targets a room when broadcasting.
* Targets a room when broadcasting. Similar to `to()`, but might feel clearer in some cases:
*
* @param room
* @return self
* @public
* @example
* io.on("connection", (socket) => {
* // disconnect all clients in the "room-101" room, except this socket
* socket.in("room-101").disconnectSockets();
* });
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public in(room: Room | Room[]): BroadcastOperator<EmitEvents, SocketData> {
public in(room: Room | Room[]) {
return this.newBroadcastOperator().in(room);
}
/**
* Excludes a room when broadcasting.
*
* @param room
* @return self
* @public
* @example
* io.on("connection", (socket) => {
* // the "foo" event will be broadcast to all connected clients, except the ones that are in the "room-101" room
* // and this socket
* socket.except("room-101").emit("foo", "bar");
*
* // with an array of rooms
* socket.except(["room-101", "room-102"]).emit("foo", "bar");
*
* // with multiple chained calls
* socket.except("room-101").except("room-102").emit("foo", "bar");
* });
*
* @param room - a room, or an array of rooms
* @return a new {@link BroadcastOperator} instance for chaining
*/
public except(
room: Room | Room[]
): BroadcastOperator<EmitEvents, SocketData> {
public except(room: Room | Room[]) {
return this.newBroadcastOperator().except(room);
}
/**
* Sends a `message` event.
*
* This method mimics the WebSocket.send() method.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
*
* @example
* io.on("connection", (socket) => {
* socket.send("hello");
*
* // this is equivalent to
* socket.emit("message", "hello");
* });
*
* @return self
* @public
*/
public send(...args: EventParams<EmitEvents, "message">): this {
this.emit("message", ...args);
@@ -296,10 +414,9 @@ export class Socket<
}
/**
* Sends a `message` event.
* Sends a `message` event. Alias of {@link send}.
*
* @return self
* @public
*/
public write(...args: EventParams<EmitEvents, "message">): this {
this.emit("message", ...args);
@@ -325,9 +442,17 @@ export class Socket<
/**
* Joins a room.
*
* @example
* io.on("connection", (socket) => {
* // join a single room
* socket.join("room1");
*
* // join multiple rooms
* socket.join(["room1", "room2"]);
* });
*
* @param {String|Array} rooms - room or array of rooms
* @return a Promise or nothing, depending on the adapter
* @public
*/
public join(rooms: Room | Array<Room>): Promise<void> | void {
debug("join room %s", rooms);
@@ -341,9 +466,17 @@ export class Socket<
/**
* Leaves a room.
*
* @example
* io.on("connection", (socket) => {
* // leave a single room
* socket.leave("room1");
*
* // leave multiple rooms
* socket.leave("room1").leave("room2");
* });
*
* @param {String} room
* @return a Promise or nothing, depending on the adapter
* @public
*/
public leave(room: string): Promise<void> | void {
debug("leave room %s", room);
@@ -507,11 +640,11 @@ export class Socket<
*
* @private
*/
_onclose(reason: string): this | undefined {
_onclose(reason: DisconnectReason): this | undefined {
if (!this.connected) return this;
debug("closing socket - reason %s", reason);
this.emitReserved("disconnecting", reason);
this.leaveAll();
this._cleanup();
this.nsp._remove(this);
this.client._remove(this);
this.connected = false;
@@ -519,6 +652,16 @@ export class Socket<
return;
}
/**
* Makes the socket leave all the rooms it was part of and prevents it from joining any other room
*
* @private
*/
_cleanup() {
this.leaveAll();
this.join = noop;
}
/**
* Produces an `error` packet.
*
@@ -533,10 +676,17 @@ export class Socket<
/**
* Disconnects this client.
*
* @param {Boolean} close - if `true`, closes the underlying connection
* @return {Socket} self
* @example
* io.on("connection", (socket) => {
* // disconnect this socket (the connection might be kept alive for other namespaces)
* socket.disconnect();
*
* @public
* // disconnect this socket and close the underlying connection
* socket.disconnect(true);
* })
*
* @param {Boolean} close - if `true`, closes the underlying connection
* @return self
*/
public disconnect(close = false): this {
if (!this.connected) return this;
@@ -552,9 +702,13 @@ export class Socket<
/**
* Sets the compress flag.
*
* @example
* io.on("connection", (socket) => {
* socket.compress(false).emit("hello");
* });
*
* @param {Boolean} compress - if `true`, compresses the sending data
* @return {Socket} self
* @public
*/
public compress(compress: boolean): this {
this.flags.compress = compress;
@@ -566,8 +720,12 @@ export class Socket<
* 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).
*
* @example
* io.on("connection", (socket) => {
* socket.volatile.emit("hello"); // the client may or may not receive it
* });
*
* @return {Socket} self
* @public
*/
public get volatile(): this {
this.flags.volatile = true;
@@ -578,20 +736,30 @@ export class Socket<
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the
* sender.
*
* @return {Socket} self
* @public
* @example
* io.on("connection", (socket) => {
* // the “foo” event will be broadcast to all connected clients, except this socket
* socket.broadcast.emit("foo", "bar");
* });
*
* @return a new {@link BroadcastOperator} instance for chaining
*/
public get broadcast(): BroadcastOperator<EmitEvents, SocketData> {
public get broadcast() {
return this.newBroadcastOperator();
}
/**
* Sets a modifier for a subsequent event emission that the event data will only be broadcast to the current node.
*
* @return {Socket} self
* @public
* @example
* io.on("connection", (socket) => {
* // the “foo” event will be broadcast to all connected clients on this node, except this socket
* socket.local.emit("foo", "bar");
* });
*
* @return a new {@link BroadcastOperator} instance for chaining
*/
public get local(): BroadcastOperator<EmitEvents, SocketData> {
public get local() {
return this.newBroadcastOperator().local;
}
@@ -599,16 +767,16 @@ export class Socket<
* Sets a modifier for a subsequent event emission that the callback will be called with an error when the
* given number of milliseconds have elapsed without an acknowledgement from the client:
*
* ```
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the client did not acknowledge the event in the given delay
* }
* @example
* io.on("connection", (socket) => {
* socket.timeout(5000).emit("my-event", (err) => {
* if (err) {
* // the client did not acknowledge the event in the given delay
* }
* });
* });
* ```
*
* @returns self
* @public
*/
public timeout(timeout: number): this {
this.flags.timeout = timeout;
@@ -640,9 +808,25 @@ export class Socket<
/**
* Sets up socket middleware.
*
* @example
* io.on("connection", (socket) => {
* socket.use(([event, ...args], next) => {
* if (isUnauthorized(event)) {
* return next(new Error("unauthorized event"));
* }
* // do not forget to call next
* next();
* });
*
* socket.on("error", (err) => {
* if (err && err.message === "unauthorized event") {
* socket.disconnect();
* }
* });
* });
*
* @param {Function} fn - middleware function (event, next)
* @return {Socket} self
* @public
*/
public use(fn: (event: Event, next: (err?: Error) => void) => void): this {
this.fns.push(fn);
@@ -685,8 +869,6 @@ export class Socket<
/**
* A reference to the request that originated the underlying Engine.IO Socket.
*
* @public
*/
public get request(): IncomingMessage {
return this.client.request;
@@ -695,14 +877,30 @@ export class Socket<
/**
* A reference to the underlying Client transport connection (Engine.IO Socket object).
*
* @public
* @example
* io.on("connection", (socket) => {
* console.log(socket.conn.transport.name); // prints "polling" or "websocket"
*
* socket.conn.once("upgrade", () => {
* console.log(socket.conn.transport.name); // prints "websocket"
* });
* });
*/
public get conn() {
return this.client.conn;
}
/**
* @public
* Returns the rooms the socket is currently in.
*
* @example
* io.on("connection", (socket) => {
* console.log(socket.rooms); // Set { <socket.id> }
*
* socket.join("room1");
*
* console.log(socket.rooms); // Set { <socket.id>, "room1" }
* });
*/
public get rooms(): Set<Room> {
return this.adapter.socketRooms(this.id) || new Set();
@@ -712,8 +910,14 @@ export class Socket<
* Adds a listener that will be fired when any event is received. The event name is passed as the first argument to
* the callback.
*
* @example
* io.on("connection", (socket) => {
* socket.onAny((event, ...args) => {
* console.log(`got event ${event}`);
* });
* });
*
* @param listener
* @public
*/
public onAny(listener: (...args: any[]) => void): this {
this._anyListeners = this._anyListeners || [];
@@ -726,7 +930,6 @@ export class Socket<
* the callback. The listener is added to the beginning of the listeners array.
*
* @param listener
* @public
*/
public prependAny(listener: (...args: any[]) => void): this {
this._anyListeners = this._anyListeners || [];
@@ -737,8 +940,22 @@ export class Socket<
/**
* Removes the listener that will be fired when any event is received.
*
* @example
* io.on("connection", (socket) => {
* const catchAllListener = (event, ...args) => {
* console.log(`got event ${event}`);
* }
*
* socket.onAny(catchAllListener);
*
* // remove a specific listener
* socket.offAny(catchAllListener);
*
* // or remove all listeners
* socket.offAny();
* });
*
* @param listener
* @public
*/
public offAny(listener?: (...args: any[]) => void): this {
if (!this._anyListeners) {
@@ -761,28 +978,25 @@ export class Socket<
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*
* @public
*/
public listenersAny() {
return this._anyListeners || [];
}
/**
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback.
* Adds a listener that will be fired when any event is sent. The event name is passed as the first argument to
* the callback.
*
* @param listener
* Note: acknowledgements sent to the client are not included.
*
* <pre><code>
*
* socket.onAnyOutgoing((event, ...args) => {
* console.log(event);
* @example
* io.on("connection", (socket) => {
* socket.onAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
* });
*
* </pre></code>
*
* @public
* @param listener
*/
public onAnyOutgoing(listener: (...args: any[]) => void): this {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
@@ -794,17 +1008,14 @@ export class Socket<
* Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
* callback. The listener is added to the beginning of the listeners array.
*
* @param listener
*
* <pre><code>
*
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(event);
* @example
* io.on("connection", (socket) => {
* socket.prependAnyOutgoing((event, ...args) => {
* console.log(`sent event ${event}`);
* });
* });
*
* </pre></code>
*
* @public
* @param listener
*/
public prependAnyOutgoing(listener: (...args: any[]) => void): this {
this._anyOutgoingListeners = this._anyOutgoingListeners || [];
@@ -813,24 +1024,24 @@ export class Socket<
}
/**
* Removes the listener that will be fired when any event is emitted.
* Removes the listener that will be fired when any event is sent.
*
* @param listener
* @example
* io.on("connection", (socket) => {
* const catchAllListener = (event, ...args) => {
* console.log(`sent event ${event}`);
* }
*
* <pre><code>
* socket.onAnyOutgoing(catchAllListener);
*
* const handler = (event, ...args) => {
* console.log(event);
* }
* // remove a specific listener
* socket.offAnyOutgoing(catchAllListener);
*
* socket.onAnyOutgoing(handler);
* // or remove all listeners
* socket.offAnyOutgoing();
* });
*
* // then later
* socket.offAnyOutgoing(handler);
*
* </pre></code>
*
* @public
* @param listener - the catch-all listener
*/
public offAnyOutgoing(listener?: (...args: any[]) => void): this {
if (!this._anyOutgoingListeners) {
@@ -853,8 +1064,6 @@ export class Socket<
/**
* Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
* e.g. to remove listeners.
*
* @public
*/
public listenersAnyOutgoing() {
return this._anyOutgoingListeners || [];
@@ -876,10 +1085,10 @@ export class Socket<
}
}
private newBroadcastOperator(): BroadcastOperator<EmitEvents, SocketData> {
private newBroadcastOperator() {
const flags = Object.assign({}, this.flags);
this.flags = {};
return new BroadcastOperator(
return new BroadcastOperator<EmitEvents, SocketData>(
this.adapter,
new Set<Room>(),
new Set<Room>([this.id]),

View File

@@ -25,7 +25,9 @@ export function patchAdapter(app /* : TemplatedApp */) {
if (isNew) {
socket.conn.on("upgrade", () => {
const rooms = this.sids.get(id);
subscribe(this.nsp.name, socket, isNew, rooms);
if (rooms) {
subscribe(this.nsp.name, socket, isNew, rooms);
}
});
}
};

5359
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "socket.io",
"version": "4.5.1",
"version": "4.5.4",
"description": "node.js realtime framework server",
"keywords": [
"realtime",
@@ -40,7 +40,7 @@
"compile": "rimraf ./dist && tsc",
"test": "npm run format:check && npm run compile && npm run test:types && npm run test:unit",
"test:types": "tsd",
"test:unit": "nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/socket.io.ts",
"test:unit": "nyc mocha --require ts-node/register --reporter spec --slow 200 --bail --timeout 10000 test/index.ts",
"format:check": "prettier --check \"lib/**/*.ts\" \"test/**/*.ts\"",
"format:fix": "prettier --write \"lib/**/*.ts\" \"test/**/*.ts\"",
"prepack": "npm run compile"
@@ -49,23 +49,23 @@
"accepts": "~1.3.4",
"base64id": "~2.0.0",
"debug": "~4.3.2",
"engine.io": "~6.2.0",
"engine.io": "~6.2.1",
"socket.io-adapter": "~2.4.0",
"socket.io-parser": "~4.0.4"
"socket.io-parser": "~4.2.1"
},
"devDependencies": {
"@types/mocha": "^9.0.0",
"expect.js": "0.3.1",
"mocha": "^3.5.3",
"mocha": "^10.0.0",
"nyc": "^15.1.0",
"prettier": "^2.3.2",
"rimraf": "^3.0.2",
"socket.io-client": "4.5.1",
"socket.io-client": "4.5.4",
"socket.io-client-v2": "npm:socket.io-client@^2.4.0",
"superagent": "^6.1.0",
"superagent": "^8.0.0",
"supertest": "^6.1.6",
"ts-node": "^10.2.1",
"tsd": "^0.17.0",
"tsd": "^0.21.0",
"typescript": "^4.4.2",
"uWebSockets.js": "github:uNetworking/uWebSockets.js#v20.0.0"
},

181
test/close.ts Normal file
View File

@@ -0,0 +1,181 @@
import { createServer } from "http";
import { io as ioc } from "socket.io-client";
import { join } from "path";
import { exec } from "child_process";
import { Server } from "..";
import expect from "expect.js";
import { createClient, getPort } from "./support/util";
import request from "supertest";
// TODO: update superagent as latest release now supports promises
const eioHandshake = (httpServer): Promise<string> => {
return new Promise((resolve) => {
request(httpServer)
.get("/socket.io/")
.query({ transport: "polling", EIO: 4 })
.end((err, res) => {
const sid = JSON.parse(res.text.substring(1)).sid;
resolve(sid);
});
});
};
const eioPush = (httpServer, sid: string, body: string): Promise<void> => {
return new Promise((resolve) => {
request(httpServer)
.post("/socket.io/")
.send(body)
.query({ transport: "polling", EIO: 4, sid })
.expect(200)
.end(() => {
resolve();
});
});
};
const eioPoll = (httpServer, sid): Promise<string> => {
return new Promise((resolve) => {
request(httpServer)
.get("/socket.io/")
.query({ transport: "polling", EIO: 4, sid })
.expect(200)
.end((err, res) => {
resolve(res.text);
});
});
};
describe("close", () => {
it("should be able to close sio sending a srv", (done) => {
const httpServer = createServer().listen(0);
const io = new Server(httpServer);
const port = getPort(io);
const net = require("net");
const server = net.createServer();
const clientSocket = createClient(io, "/", { reconnection: false });
clientSocket.on("disconnect", () => {
expect(io.sockets.sockets.size).to.equal(0);
server.listen(port);
});
clientSocket.on("connect", () => {
expect(io.sockets.sockets.size).to.equal(1);
io.close();
});
server.once("listening", () => {
// PORT should be free
server.close((error) => {
expect(error).to.be(undefined);
done();
});
});
});
it("should be able to close sio sending a srv", (done) => {
const io = new Server(0);
const port = getPort(io);
const net = require("net");
const server = net.createServer();
const clientSocket = ioc("ws://0.0.0.0:" + port, {
reconnection: false,
});
clientSocket.on("disconnect", () => {
expect(io.sockets.sockets.size).to.equal(0);
server.listen(port);
});
clientSocket.on("connect", () => {
expect(io.sockets.sockets.size).to.equal(1);
io.close();
});
server.once("listening", () => {
// PORT should be free
server.close((error) => {
expect(error).to.be(undefined);
done();
});
});
});
describe("graceful close", () => {
function fixture(filename) {
return (
'"' +
process.execPath +
'" "' +
join(__dirname, "fixtures", filename) +
'"'
);
}
it("should stop socket and timers", (done) => {
exec(fixture("server-close.ts"), done);
});
});
describe("protocol violations", () => {
it("should close the connection when receiving several CONNECT packets", async () => {
const httpServer = createServer();
const io = new Server(httpServer);
httpServer.listen(0);
const sid = await eioHandshake(httpServer);
// send a first CONNECT packet
await eioPush(httpServer, sid, "40");
// send another CONNECT packet
await eioPush(httpServer, sid, "40");
// session is cleanly closed (not discarded, see 'client.close()')
// first, we receive the Socket.IO handshake response
await eioPoll(httpServer, sid);
// then a close packet
const body = await eioPoll(httpServer, sid);
expect(body).to.be("6\u001e1");
io.close();
});
it("should close the connection when receiving an EVENT packet while not connected", async () => {
const httpServer = createServer();
const io = new Server(httpServer);
httpServer.listen(0);
const sid = await eioHandshake(httpServer);
// send an EVENT packet
await eioPush(httpServer, sid, '42["some event"]');
// session is cleanly closed, we receive a close packet
const body = await eioPoll(httpServer, sid);
expect(body).to.be("6\u001e1");
io.close();
});
it("should close the connection when receiving an invalid packet", async () => {
const httpServer = createServer();
const io = new Server(httpServer);
httpServer.listen(0);
const sid = await eioHandshake(httpServer);
// send a CONNECT packet
await eioPush(httpServer, sid, "40");
// send an invalid packet
await eioPush(httpServer, sid, "4abc");
// session is cleanly closed (not discarded, see 'client.close()')
// first, we receive the Socket.IO handshake response
await eioPoll(httpServer, sid);
// then a close packet
const body = await eioPoll(httpServer, sid);
expect(body).to.be("6\u001e1");
io.close();
});
});
});

87
test/handshake.ts Normal file
View File

@@ -0,0 +1,87 @@
import { Server } from "..";
import expect from "expect.js";
import { getPort, success } from "./support/util";
describe("handshake", () => {
const request = require("superagent");
it("should send the Access-Control-Allow-xxx headers on OPTIONS request", (done) => {
const io = new Server(0, {
cors: {
origin: "http://localhost:54023",
methods: ["GET", "POST"],
allowedHeaders: ["content-type"],
credentials: true,
},
});
request
.options(`http://localhost:${getPort(io)}/socket.io/default/`)
.query({ transport: "polling", EIO: 4 })
.set("Origin", "http://localhost:54023")
.end((err, res) => {
expect(res.status).to.be(204);
expect(res.headers["access-control-allow-origin"]).to.be(
"http://localhost:54023"
);
expect(res.headers["access-control-allow-methods"]).to.be("GET,POST");
expect(res.headers["access-control-allow-headers"]).to.be(
"content-type"
);
expect(res.headers["access-control-allow-credentials"]).to.be("true");
success(done, io);
});
});
it("should send the Access-Control-Allow-xxx headers on GET request", (done) => {
const io = new Server(0, {
cors: {
origin: "http://localhost:54024",
methods: ["GET", "POST"],
allowedHeaders: ["content-type"],
credentials: true,
},
});
request
.get(`http://localhost:${getPort(io)}/socket.io/default/`)
.query({ transport: "polling", EIO: 4 })
.set("Origin", "http://localhost:54024")
.end((err, res) => {
expect(res.status).to.be(200);
expect(res.headers["access-control-allow-origin"]).to.be(
"http://localhost:54024"
);
expect(res.headers["access-control-allow-credentials"]).to.be("true");
success(done, io);
});
});
it("should allow request if custom function in opts.allowRequest returns true", (done) => {
const io = new Server(0, {
allowRequest: (req, callback) => callback(null, true),
});
request
.get(`http://localhost:${getPort(io)}/socket.io/default/`)
.query({ transport: "polling", EIO: 4 })
.end((err, res) => {
expect(res.status).to.be(200);
success(done, io);
});
});
it("should disallow request if custom function in opts.allowRequest returns false", (done) => {
const io = new Server(0, {
allowRequest: (req, callback) => callback(null, false),
});
request
.get(`http://localhost:${getPort(io)}/socket.io/default/`)
.set("origin", "http://foo.example")
.query({ transport: "polling", EIO: 4 })
.end((err, res) => {
expect(res.status).to.be(403);
success(done, io);
});
});
});

23
test/index.ts Normal file
View File

@@ -0,0 +1,23 @@
"use strict";
import expect from "expect.js";
describe("socket.io", () => {
it("should be the same version as client", () => {
const version = require("../package").version;
expect(version).to.be(require("socket.io-client/package.json").version);
});
require("./server-attachment");
require("./handshake");
require("./close");
require("./namespaces");
require("./socket");
require("./messaging-many");
require("./middleware");
require("./socket-middleware");
require("./v2-compatibility");
require("./socket-timeout");
require("./uws");
require("./utility-methods");
});

501
test/messaging-many.ts Normal file
View File

@@ -0,0 +1,501 @@
import { Server } from "..";
import expect from "expect.js";
import {
createClient,
createPartialDone,
success,
successFn,
waitFor,
} from "./support/util";
describe("messaging many", () => {
it("emits to a namespace", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/test");
const partialDone = createPartialDone(
2,
successFn(done, io, socket1, socket2, socket3)
);
socket1.on("a", (a) => {
expect(a).to.be("b");
partialDone();
});
socket2.on("a", (a) => {
expect(a).to.be("b");
partialDone();
});
socket3.on("a", () => {
done(new Error("not"));
});
let sockets = 3;
io.on("connection", () => {
--sockets || emit();
});
io.of("/test", () => {
--sockets || emit();
});
function emit() {
io.emit("a", "b");
}
});
it("emits binary data to a namespace", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/test");
const partialDone = createPartialDone(
2,
successFn(done, io, socket1, socket2, socket3)
);
socket1.on("bin", (a) => {
expect(Buffer.isBuffer(a)).to.be(true);
partialDone();
});
socket2.on("bin", (a) => {
expect(Buffer.isBuffer(a)).to.be(true);
partialDone();
});
socket3.on("bin", () => {
done(new Error("not"));
});
let sockets = 3;
io.on("connection", () => {
--sockets || emit();
});
io.of("/test", () => {
--sockets || emit();
});
function emit() {
io.emit("bin", Buffer.alloc(10));
}
});
it("emits to the rest", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/test");
socket1.on("a", (a) => {
expect(a).to.be("b");
socket1.emit("finish");
});
socket2.emit("broadcast");
socket2.on("a", () => {
done(new Error("done"));
});
socket3.on("a", () => {
done(new Error("not"));
});
io.on("connection", (socket) => {
socket.on("broadcast", () => {
socket.broadcast.emit("a", "b");
});
socket.on("finish", () => {
success(done, io, socket1, socket2, socket3);
});
});
});
it("emits to rooms", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
socket2.on("a", () => {
done(new Error("not"));
});
socket1.on("a", () => {
success(done, io, socket1, socket2);
});
socket1.emit("join", "woot");
socket1.emit("emit", "woot");
io.on("connection", (socket) => {
socket.on("join", (room, fn) => {
socket.join(room);
fn && fn();
});
socket.on("emit", (room) => {
io.in(room).emit("a");
});
});
});
it("emits to rooms avoiding dupes", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const partialDone = createPartialDone(
2,
successFn(done, io, socket1, socket2)
);
socket2.on("a", () => {
done(new Error("not"));
});
socket1.on("a", partialDone);
socket2.on("b", partialDone);
socket1.emit("join", "woot");
socket1.emit("join", "test");
socket2.emit("join", "third", () => {
socket2.emit("emit");
});
io.on("connection", (socket) => {
socket.on("join", (room, fn) => {
socket.join(room);
fn && fn();
});
socket.on("emit", () => {
io.in("woot").in("test").emit("a");
io.in("third").emit("b");
});
});
});
it("broadcasts to rooms", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
const partialDone = createPartialDone(
2,
successFn(done, io, socket1, socket2, socket3)
);
socket1.emit("join", "woot");
socket2.emit("join", "test");
socket3.emit("join", "test", () => {
socket3.emit("broadcast");
});
socket1.on("a", () => {
done(new Error("not"));
});
socket2.on("a", () => {
partialDone();
});
socket3.on("a", () => {
done(new Error("not"));
});
socket3.on("b", () => {
partialDone();
});
io.on("connection", (socket) => {
socket.on("join", (room, fn) => {
socket.join(room);
fn && fn();
});
socket.on("broadcast", () => {
socket.broadcast.to("test").emit("a");
socket.emit("b");
});
});
});
it("broadcasts binary data to rooms", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
const partialDone = createPartialDone(
2,
successFn(done, io, socket1, socket2, socket3)
);
socket1.emit("join", "woot");
socket2.emit("join", "test");
socket3.emit("join", "test", () => {
socket3.emit("broadcast");
});
socket1.on("bin", (data) => {
throw new Error("got bin in socket1");
});
socket2.on("bin", (data) => {
expect(Buffer.isBuffer(data)).to.be(true);
partialDone();
});
socket2.on("bin2", (data) => {
throw new Error("socket2 got bin2");
});
socket3.on("bin", (data) => {
throw new Error("socket3 got bin");
});
socket3.on("bin2", (data) => {
expect(Buffer.isBuffer(data)).to.be(true);
partialDone();
});
io.on("connection", (socket) => {
socket.on("join", (room, fn) => {
socket.join(room);
fn && fn();
});
socket.on("broadcast", () => {
socket.broadcast.to("test").emit("bin", Buffer.alloc(5));
socket.emit("bin2", Buffer.alloc(5));
});
});
});
it("keeps track of rooms", (done) => {
const io = new Server(0);
const socket = createClient(io);
io.on("connection", (s) => {
s.join("a");
expect(s.rooms).to.contain(s.id, "a");
s.join("b");
expect(s.rooms).to.contain(s.id, "a", "b");
s.join("c");
expect(s.rooms).to.contain(s.id, "a", "b", "c");
s.leave("b");
expect(s.rooms).to.contain(s.id, "a", "c");
(s as any).leaveAll();
expect(s.rooms.size).to.eql(0);
success(done, io, socket);
});
});
it("deletes empty rooms", (done) => {
const io = new Server(0);
const socket = createClient(io);
io.on("connection", (s) => {
s.join("a");
expect(s.nsp.adapter.rooms).to.contain("a");
s.leave("a");
expect(s.nsp.adapter.rooms).to.not.contain("a");
success(done, io, socket);
});
});
it("should properly cleanup left rooms", (done) => {
const io = new Server(0);
const socket = createClient(io);
io.on("connection", (s) => {
s.join("a");
expect(s.rooms).to.contain(s.id, "a");
s.join("b");
expect(s.rooms).to.contain(s.id, "a", "b");
s.leave("unknown");
expect(s.rooms).to.contain(s.id, "a", "b");
(s as any).leaveAll();
expect(s.rooms.size).to.eql(0);
success(done, io, socket);
});
});
it("allows to join several rooms at once", (done) => {
const io = new Server(0);
const socket = createClient(io);
io.on("connection", (s) => {
s.join(["a", "b", "c"]);
expect(s.rooms).to.contain(s.id, "a", "b", "c");
success(done, io, socket);
});
});
it("should exclude specific sockets when broadcasting", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
socket2.on("a", () => {
done(new Error("not"));
});
socket3.on("a", () => {
done(new Error("not"));
});
socket1.on("a", successFn(done, io, socket1, socket2, socket3));
io.on("connection", (socket) => {
socket.on("exclude", (id) => {
socket.broadcast.except(id).emit("a");
});
});
socket2.on("connect", () => {
socket3.emit("exclude", socket2.id);
});
});
it("should exclude a specific room when broadcasting", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
socket2.on("a", () => {
done(new Error("not"));
});
socket3.on("a", () => {
done(new Error("not"));
});
socket1.on("a", successFn(done, io, socket1, socket2, socket3));
io.on("connection", (socket) => {
socket.on("join", (room, cb) => {
socket.join(room);
cb();
});
socket.on("broadcast", () => {
socket.broadcast.except("room1").emit("a");
});
});
socket2.emit("join", "room1", () => {
socket3.emit("broadcast");
});
});
it("should return an immutable broadcast operator", (done) => {
const io = new Server(0);
const clientSocket = createClient(io);
io.on("connection", (socket) => {
const operator = socket.local
.compress(false)
.to(["room1", "room2"])
.except("room3");
operator.compress(true).emit("hello");
operator.volatile.emit("hello");
operator.to("room4").emit("hello");
operator.except("room5").emit("hello");
socket.emit("hello");
socket.to("room6").emit("hello");
// @ts-ignore
expect(operator.rooms).to.contain("room1", "room2");
// @ts-ignore
expect(operator.rooms).to.not.contain("room4", "room5", "room6");
// @ts-ignore
expect(operator.exceptRooms).to.contain("room3");
// @ts-ignore
expect(operator.flags).to.eql({ local: true, compress: false });
success(done, io, clientSocket);
});
});
it("should broadcast and expect multiple acknowledgements", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
socket1.on("some event", (cb) => {
cb(1);
});
socket2.on("some event", (cb) => {
cb(2);
});
socket3.on("some event", (cb) => {
cb(3);
});
Promise.all([
waitFor(socket1, "connect"),
waitFor(socket2, "connect"),
waitFor(socket3, "connect"),
]).then(() => {
io.timeout(2000).emit("some event", (err, responses) => {
expect(err).to.be(null);
expect(responses).to.have.length(3);
expect(responses).to.contain(1, 2, 3);
success(done, io, socket1, socket2, socket3);
});
});
});
it("should fail when a client does not acknowledge the event in the given delay", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
socket1.on("some event", (cb) => {
cb(1);
});
socket2.on("some event", (cb) => {
cb(2);
});
socket3.on("some event", () => {
// timeout
});
Promise.all([
waitFor(socket1, "connect"),
waitFor(socket2, "connect"),
waitFor(socket3, "connect"),
]).then(() => {
io.timeout(200).emit("some event", (err, responses) => {
expect(err).to.be.an(Error);
expect(responses).to.have.length(2);
expect(responses).to.contain(1, 2);
success(done, io, socket1, socket2, socket3);
});
});
});
it("should broadcast and return if the packet is sent to 0 client", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/", { multiplex: false });
const socket2 = createClient(io, "/", { multiplex: false });
const socket3 = createClient(io, "/", { multiplex: false });
socket1.on("some event", () => {
done(new Error("should not happen"));
});
socket2.on("some event", () => {
done(new Error("should not happen"));
});
socket3.on("some event", () => {
done(new Error("should not happen"));
});
io.to("room123")
.timeout(200)
.emit("some event", (err, responses) => {
expect(err).to.be(null);
expect(responses).to.have.length(0);
success(done, io, socket1, socket2, socket3);
});
});
});

210
test/middleware.ts Normal file
View File

@@ -0,0 +1,210 @@
import { Server, Socket } from "..";
import expect from "expect.js";
import {
success,
createClient,
successFn,
createPartialDone,
} from "./support/util";
describe("middleware", () => {
it("should call functions", (done) => {
const io = new Server(0);
let run = 0;
io.use((socket, next) => {
expect(socket).to.be.a(Socket);
run++;
next();
});
io.use((socket, next) => {
expect(socket).to.be.a(Socket);
run++;
next();
});
const socket = createClient(io);
socket.on("connect", () => {
expect(run).to.be(2);
success(done, io, socket);
});
});
it("should pass errors", (done) => {
const io = new Server(0);
io.use((socket, next) => {
next(new Error("Authentication error"));
});
io.use((socket, next) => {
done(new Error("nope"));
});
const socket = createClient(io);
socket.on("connect", () => {
done(new Error("nope"));
});
socket.on("connect_error", (err) => {
expect(err.message).to.be("Authentication error");
success(done, io, socket);
});
});
it("should pass an object", (done) => {
const io = new Server(0);
io.use((socket, next) => {
const err = new Error("Authentication error");
// @ts-ignore
err.data = { a: "b", c: 3 };
next(err);
});
const socket = createClient(io);
socket.on("connect", () => {
done(new Error("nope"));
});
socket.on("connect_error", (err) => {
expect(err).to.be.an(Error);
expect(err.message).to.eql("Authentication error");
// @ts-ignore
expect(err.data).to.eql({ a: "b", c: 3 });
success(done, io, socket);
});
});
it("should only call connection after fns", (done) => {
const io = new Server(0);
io.use((socket: any, next) => {
socket.name = "guillermo";
next();
});
const clientSocket = createClient(io);
io.on("connection", (socket) => {
expect((socket as any).name).to.be("guillermo");
success(done, io, clientSocket);
});
});
it("should only call connection after (lengthy) fns", (done) => {
const io = new Server(0);
let authenticated = false;
io.use((socket, next) => {
setTimeout(() => {
authenticated = true;
next();
}, 300);
});
const socket = createClient(io);
socket.on("connect", () => {
expect(authenticated).to.be(true);
success(done, io, socket);
});
});
it("should be ignored if socket gets closed", (done) => {
const io = new Server(0);
let socket;
io.use((s, next) => {
socket.io.engine.close();
s.client.conn.on("close", () => {
process.nextTick(next);
setTimeout(() => {
success(done, io, socket);
}, 50);
});
});
socket = createClient(io);
io.on("connection", (socket) => {
done(new Error("should not fire"));
});
});
it("should call functions in expected order", (done) => {
const io = new Server(0);
const result: number[] = [];
io.use(() => {
done(new Error("should not fire"));
});
io.of("/chat").use((socket, next) => {
result.push(1);
setTimeout(next, 50);
});
io.of("/chat").use((socket, next) => {
result.push(2);
setTimeout(next, 50);
});
io.of("/chat").use((socket, next) => {
result.push(3);
setTimeout(next, 50);
});
const chat = createClient(io, "/chat");
chat.on("connect", () => {
expect(result).to.eql([1, 2, 3]);
success(done, io, chat);
});
});
it("should disable the merge of handshake packets", (done) => {
const io = new Server(0);
io.use((socket, next) => {
next();
});
const socket = createClient(io);
socket.on("connect", successFn(done, io, socket));
});
it("should work with a custom namespace", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/");
const socket2 = createClient(io, "/chat");
const partialDone = createPartialDone(
2,
successFn(done, io, socket1, socket2)
);
io.of("/chat").use((socket, next) => {
next();
});
socket1.on("connect", partialDone);
socket2.on("connect", partialDone);
});
it("should only set `connected` to true after the middleware execution", (done) => {
const io = new Server(0);
const clientSocket = createClient(io, "/");
io.use((socket, next) => {
expect(socket.connected).to.be(false);
expect(socket.disconnected).to.be(true);
next();
});
io.on("connection", (socket) => {
expect(socket.connected).to.be(true);
expect(socket.disconnected).to.be(false);
success(done, io, clientSocket);
});
});
});

575
test/namespaces.ts Normal file
View File

@@ -0,0 +1,575 @@
import type { SocketId } from "socket.io-adapter";
import { Server, Namespace, Socket } from "..";
import expect from "expect.js";
import {
success,
createClient,
successFn,
createPartialDone,
} from "./support/util";
describe("namespaces", () => {
it("should be accessible through .sockets", () => {
const io = new Server();
expect(io.sockets).to.be.a(Namespace);
});
it("should be aliased", () => {
const io = new Server();
expect(io.use).to.be.a("function");
expect(io.to).to.be.a("function");
expect(io["in"]).to.be.a("function");
expect(io.emit).to.be.a("function");
expect(io.send).to.be.a("function");
expect(io.write).to.be.a("function");
expect(io.allSockets).to.be.a("function");
expect(io.compress).to.be.a("function");
});
it("should return an immutable broadcast operator", () => {
const io = new Server();
const operator = io.local.to(["room1", "room2"]).except("room3");
operator.compress(true).emit("hello");
operator.volatile.emit("hello");
operator.to("room4").emit("hello");
operator.except("room5").emit("hello");
io.to("room6").emit("hello");
// @ts-ignore
expect(operator.rooms).to.contain("room1", "room2");
// @ts-ignore
expect(operator.exceptRooms).to.contain("room3");
// @ts-ignore
expect(operator.flags).to.eql({ local: true });
});
it("should automatically connect", (done) => {
const io = new Server(0);
const socket = createClient(io);
socket.on("connect", successFn(done, io, socket));
});
it("should fire a `connection` event", (done) => {
const io = new Server(0);
const clientSocket = createClient(io);
io.on("connection", (socket) => {
expect(socket).to.be.a(Socket);
success(done, io, clientSocket);
});
});
it("should fire a `connect` event", (done) => {
const io = new Server(0);
const clientSocket = createClient(io);
io.on("connect", (socket) => {
expect(socket).to.be.a(Socket);
success(done, io, clientSocket);
});
});
it("should work with many sockets", (done) => {
const io = new Server(0);
io.of("/chat");
io.of("/news");
const chat = createClient(io, "/chat");
const news = createClient(io, "/news");
let total = 2;
chat.on("connect", () => {
--total || success(done, io, chat, news);
});
news.on("connect", () => {
--total || success(done, io, chat, news);
});
});
it('should be able to equivalently start with "" or "/" on server', (done) => {
const io = new Server(0);
const c1 = createClient(io, "/");
const c2 = createClient(io, "/abc");
let total = 2;
io.of("").on("connection", () => {
--total || success(done, io, c1, c2);
});
io.of("abc").on("connection", () => {
--total || success(done, io, c1, c2);
});
});
it('should be equivalent for "" and "/" on client', (done) => {
const io = new Server(0);
const c1 = createClient(io, "");
io.of("/").on("connection", successFn(done, io, c1));
});
it("should work with `of` and many sockets", (done) => {
const io = new Server(0);
const chat = createClient(io, "/chat");
const news = createClient(io, "/news");
let total = 2;
io.of("/news").on("connection", (socket) => {
expect(socket).to.be.a(Socket);
--total || success(done, io, chat, news);
});
io.of("/news").on("connection", (socket) => {
expect(socket).to.be.a(Socket);
--total || success(done, io, chat, news);
});
});
it("should work with `of` second param", (done) => {
const io = new Server(0);
const chat = createClient(io, "/chat");
const news = createClient(io, "/news");
let total = 2;
io.of("/news", (socket) => {
expect(socket).to.be.a(Socket);
--total || success(done, io, chat, news);
});
io.of("/news", (socket) => {
expect(socket).to.be.a(Socket);
--total || success(done, io, chat, news);
});
});
it("should disconnect upon transport disconnection", (done) => {
const io = new Server(0);
const chat = createClient(io, "/chat");
const news = createClient(io, "/news");
let total = 2;
let totald = 2;
let s;
io.of("/news", (socket) => {
socket.on("disconnect", (reason) => {
--totald || success(done, io, chat, news);
});
--total || close();
});
io.of("/chat", (socket) => {
s = socket;
socket.on("disconnect", (reason) => {
--totald || success(done, io, chat, news);
});
--total || close();
});
function close() {
s.disconnect(true);
}
});
it("should fire a `disconnecting` event just before leaving all rooms", (done) => {
const io = new Server(0);
const socket = createClient(io);
io.on("connection", (s) => {
s.join("a");
// FIXME not sure why process.nextTick() is needed here
process.nextTick(() => s.disconnect());
let total = 2;
s.on("disconnecting", (reason) => {
expect(s.rooms).to.contain(s.id, "a");
total--;
});
s.on("disconnect", (reason) => {
expect(s.rooms.size).to.eql(0);
--total || success(done, io, socket);
});
});
});
it("should return error connecting to non-existent namespace", (done) => {
const io = new Server(0);
const socket = createClient(io, "/doesnotexist");
socket.on("connect_error", (err) => {
expect(err.message).to.be("Invalid namespace");
success(done, io);
});
});
it("should not reuse same-namespace connections", (done) => {
const io = new Server(0);
const clientSocket1 = createClient(io);
const clientSocket2 = createClient(io);
let connections = 0;
io.on("connection", () => {
connections++;
if (connections === 2) {
success(done, io, clientSocket1, clientSocket2);
}
});
});
it("should find all clients in a namespace", (done) => {
const io = new Server(0);
const chatSids: string[] = [];
let otherSid: SocketId | null = null;
const c1 = createClient(io, "/chat");
const c2 = createClient(io, "/chat", { forceNew: true });
const c3 = createClient(io, "/other", { forceNew: true });
let total = 3;
io.of("/chat").on("connection", (socket) => {
chatSids.push(socket.id);
--total || getSockets();
});
io.of("/other").on("connection", (socket) => {
otherSid = socket.id;
--total || getSockets();
});
async function getSockets() {
const sids = await io.of("/chat").allSockets();
expect(sids).to.contain(chatSids[0], chatSids[1]);
expect(sids).to.not.contain(otherSid);
success(done, io, c1, c2, c3);
}
});
it("should find all clients in a namespace room", (done) => {
const io = new Server(0);
let chatFooSid: SocketId | null = null;
let chatBarSid: SocketId | null = null;
let otherSid: SocketId | null = null;
const c1 = createClient(io, "/chat");
const c2 = createClient(io, "/chat", { forceNew: true });
const c3 = createClient(io, "/other", { forceNew: true });
let chatIndex = 0;
let total = 3;
io.of("/chat").on("connection", (socket) => {
if (chatIndex++) {
socket.join("foo");
chatFooSid = socket.id;
--total || getSockets();
} else {
socket.join("bar");
chatBarSid = socket.id;
--total || getSockets();
}
});
io.of("/other").on("connection", (socket) => {
socket.join("foo");
otherSid = socket.id;
--total || getSockets();
});
async function getSockets() {
const sids = await io.of("/chat").in("foo").allSockets();
expect(sids).to.contain(chatFooSid);
expect(sids).to.not.contain(chatBarSid);
expect(sids).to.not.contain(otherSid);
success(done, io, c1, c2, c3);
}
});
it("should find all clients across namespace rooms", (done) => {
const io = new Server(0);
let chatFooSid: SocketId | null = null;
let chatBarSid: SocketId | null = null;
let otherSid: SocketId | null = null;
const c1 = createClient(io, "/chat");
const c2 = createClient(io, "/chat", { forceNew: true });
const c3 = createClient(io, "/other", { forceNew: true });
let chatIndex = 0;
let total = 3;
io.of("/chat").on("connection", (socket) => {
if (chatIndex++) {
socket.join("foo");
chatFooSid = socket.id;
--total || getSockets();
} else {
socket.join("bar");
chatBarSid = socket.id;
--total || getSockets();
}
});
io.of("/other").on("connection", (socket) => {
socket.join("foo");
otherSid = socket.id;
--total || getSockets();
});
async function getSockets() {
const sids = await io.of("/chat").allSockets();
expect(sids).to.contain(chatFooSid, chatBarSid);
expect(sids).to.not.contain(otherSid);
success(done, io, c1, c2, c3);
}
});
it("should not emit volatile event after regular event", (done) => {
const io = new Server(0);
let counter = 0;
io.of("/chat").on("connection", (s) => {
// Wait to make sure there are no packets being sent for opening the connection
setTimeout(() => {
io.of("/chat").emit("ev", "data");
io.of("/chat").volatile.emit("ev", "data");
}, 50);
});
const socket = createClient(io, "/chat");
socket.on("ev", () => {
counter++;
});
setTimeout(() => {
expect(counter).to.be(1);
success(done, io, socket);
}, 500);
});
it("should emit volatile event", (done) => {
const io = new Server(0);
let counter = 0;
io.of("/chat").on("connection", (s) => {
// Wait to make sure there are no packets being sent for opening the connection
setTimeout(() => {
io.of("/chat").volatile.emit("ev", "data");
}, 100);
});
const socket = createClient(io, "/chat");
socket.on("ev", () => {
counter++;
});
setTimeout(() => {
expect(counter).to.be(1);
success(done, io, socket);
}, 500);
});
it("should enable compression by default", (done) => {
const io = new Server(0);
const socket = createClient(io, "/chat");
io.of("/chat").on("connection", (s) => {
s.conn.once("packetCreate", (packet) => {
expect(packet.options.compress).to.be(true);
success(done, io, socket);
});
io.of("/chat").emit("woot", "hi");
});
});
it("should disable compression", (done) => {
const io = new Server(0);
const socket = createClient(io, "/chat");
io.of("/chat").on("connection", (s) => {
s.conn.once("packetCreate", (packet) => {
expect(packet.options.compress).to.be(false);
success(done, io, socket);
});
io.of("/chat").compress(false).emit("woot", "hi");
});
});
it("should throw on reserved event", () => {
const io = new Server();
expect(() => io.emit("connect")).to.throwException(
/"connect" is a reserved event name/
);
});
it("should close a client without namespace", (done) => {
const io = new Server(0, {
connectTimeout: 10,
});
const socket = createClient(io);
// @ts-ignore
socket.io.engine.write = () => {}; // prevent the client from sending a CONNECT packet
socket.on("disconnect", successFn(done, io, socket));
});
it("should exclude a specific socket when emitting", (done) => {
const io = new Server(0);
const socket1 = createClient(io, "/");
const socket2 = createClient(io, "/");
socket2.on("a", () => {
done(new Error("should not happen"));
});
socket1.on("a", successFn(done, io, socket1, socket2));
socket2.on("connect", () => {
io.except(socket2.id).emit("a");
});
});
it("should exclude a specific socket when emitting (in a namespace)", (done) => {
const io = new Server(0);
const nsp = io.of("/nsp");
const socket1 = createClient(io, "/nsp");
const socket2 = createClient(io, "/nsp");
socket2.on("a", () => {
done(new Error("not"));
});
socket1.on("a", successFn(done, io, socket1, socket2));
socket2.on("connect", () => {
nsp.except(socket2.id).emit("a");
});
});
it("should exclude a specific room when emitting", (done) => {
const io = new Server(0);
const nsp = io.of("/nsp");
const socket1 = createClient(io, "/nsp");
const socket2 = createClient(io, "/nsp");
socket1.on("a", successFn(done, io, socket1, socket2));
socket2.on("a", () => {
done(new Error("not"));
});
nsp.on("connection", (socket) => {
socket.on("broadcast", () => {
socket.join("room1");
nsp.except("room1").emit("a");
});
});
socket2.emit("broadcast");
});
it("should emit an 'new_namespace' event", (done) => {
const io = new Server();
io.on("new_namespace", (namespace) => {
expect(namespace.name).to.eql("/nsp");
done();
});
io.of("/nsp");
});
describe("dynamic namespaces", () => {
it("should allow connections to dynamic namespaces with a regex", (done) => {
const io = new Server(0);
const socket = createClient(io, "/dynamic-101");
const partialDone = createPartialDone(4, successFn(done, io, socket));
let dynamicNsp = io
.of(/^\/dynamic-\d+$/)
.on("connect", (socket) => {
expect(socket.nsp.name).to.be("/dynamic-101");
dynamicNsp.emit("hello", 1, "2", { 3: "4" });
partialDone();
})
.use((socket, next) => {
next();
partialDone();
});
socket.on("connect_error", (err) => {
expect().fail();
});
socket.on("connect", () => {
partialDone();
});
socket.on("hello", (a, b, c) => {
expect(a).to.eql(1);
expect(b).to.eql("2");
expect(c).to.eql({ 3: "4" });
partialDone();
});
});
it("should allow connections to dynamic namespaces with a function", (done) => {
const io = new Server(0);
const socket = createClient(io, "/dynamic-101");
io.of((name, query, next) => next(null, "/dynamic-101" === name));
socket.on("connect", successFn(done, io, socket));
});
it("should disallow connections when no dynamic namespace matches", (done) => {
const io = new Server(0);
const socket = createClient(io, "/abc");
io.of(/^\/dynamic-\d+$/);
io.of((name, query, next) => next(null, "/dynamic-101" === name));
socket.on("connect_error", (err) => {
expect(err.message).to.be("Invalid namespace");
success(done, io, socket);
});
});
it("should emit an 'new_namespace' event for a dynamic namespace", (done) => {
const io = new Server(0);
io.of(/^\/dynamic-\d+$/);
const socket = createClient(io, "/dynamic-101");
io.on("new_namespace", (namespace) => {
expect(namespace.name).to.be("/dynamic-101");
success(done, io, socket);
});
});
it("should handle race conditions with dynamic namespaces (#4136)", (done) => {
const io = new Server(0);
const counters = {
connected: 0,
created: 0,
events: 0,
};
const buffer: Function[] = [];
io.on("new_namespace", (namespace) => {
counters.created++;
});
const handler = () => {
if (++counters.events === 2) {
expect(counters.created).to.equal(1);
success(done, io, one, two);
}
};
io.of((name, query, next) => {
buffer.push(next);
if (buffer.length === 2) {
buffer.forEach((next) => next(null, true));
}
}).on("connection", (socket) => {
if (++counters.connected === 2) {
io.of("/dynamic-101").emit("message");
}
});
let one = createClient(io, "/dynamic-101");
let two = createClient(io, "/dynamic-101");
one.on("message", handler);
two.on("message", handler);
});
});
});

170
test/server-attachment.ts Normal file
View File

@@ -0,0 +1,170 @@
import { Server } from "..";
import { createServer } from "http";
import request from "supertest";
import expect from "expect.js";
import { getPort, successFn } from "./support/util";
describe("server attachment", () => {
describe("http.Server", () => {
const clientVersion = require("socket.io-client/package.json").version;
const testSource = (filename) => (done) => {
const srv = createServer();
new Server(srv);
request(srv)
.get("/socket.io/" + filename)
.buffer(true)
.end((err, res) => {
if (err) return done(err);
expect(res.headers["content-type"]).to.be("application/javascript");
expect(res.headers.etag).to.be('"' + clientVersion + '"');
expect(res.headers["x-sourcemap"]).to.be(undefined);
expect(res.text).to.match(/engine\.io/);
expect(res.status).to.be(200);
done();
});
};
const testSourceMap = (filename) => (done) => {
const srv = createServer();
new Server(srv);
request(srv)
.get("/socket.io/" + filename)
.buffer(true)
.end((err, res) => {
if (err) return done(err);
expect(res.headers["content-type"]).to.be("application/json");
expect(res.headers.etag).to.be('"' + clientVersion + '"');
expect(res.text).to.match(/engine\.io/);
expect(res.status).to.be(200);
done();
});
};
it("should serve client", testSource("socket.io.js"));
it(
"should serve client with query string",
testSource("socket.io.js?buster=" + Date.now())
);
it("should serve source map", testSourceMap("socket.io.js.map"));
it("should serve client (min)", testSource("socket.io.min.js"));
it("should serve source map (min)", testSourceMap("socket.io.min.js.map"));
it("should serve client (gzip)", (done) => {
const srv = createServer();
new Server(srv);
request(srv)
.get("/socket.io/socket.io.js")
.set("accept-encoding", "gzip,br,deflate")
.buffer(true)
.end((err, res) => {
if (err) return done(err);
expect(res.headers["content-encoding"]).to.be("gzip");
expect(res.status).to.be(200);
done();
});
});
it(
"should serve bundle with msgpack parser",
testSource("socket.io.msgpack.min.js")
);
it(
"should serve source map for bundle with msgpack parser",
testSourceMap("socket.io.msgpack.min.js.map")
);
it("should serve the ESM bundle", testSource("socket.io.esm.min.js"));
it(
"should serve the source map for the ESM bundle",
testSourceMap("socket.io.esm.min.js.map")
);
it("should handle 304", (done) => {
const srv = createServer();
new Server(srv);
request(srv)
.get("/socket.io/socket.io.js")
.set("If-None-Match", '"' + clientVersion + '"')
.end((err, res) => {
if (err) return done(err);
expect(res.statusCode).to.be(304);
done();
});
});
it("should handle 304", (done) => {
const srv = createServer();
new Server(srv);
request(srv)
.get("/socket.io/socket.io.js")
.set("If-None-Match", 'W/"' + clientVersion + '"')
.end((err, res) => {
if (err) return done(err);
expect(res.statusCode).to.be(304);
done();
});
});
it("should not serve static files", (done) => {
const srv = createServer();
new Server(srv, { serveClient: false });
request(srv).get("/socket.io/socket.io.js").expect(400, done);
});
it("should work with #attach", (done) => {
const srv = createServer((req, res) => {
res.writeHead(404);
res.end();
});
const sockets = new Server();
sockets.attach(srv);
request(srv)
.get("/socket.io/socket.io.js")
.end((err, res) => {
if (err) return done(err);
expect(res.status).to.be(200);
done();
});
});
it("should work with #attach (and merge options)", () => {
const srv = createServer((req, res) => {
res.writeHead(404);
res.end();
});
const server = new Server({
pingTimeout: 6000,
});
server.attach(srv, {
pingInterval: 24000,
});
// @ts-ignore
expect(server.eio.opts.pingTimeout).to.eql(6000);
// @ts-ignore
expect(server.eio.opts.pingInterval).to.eql(24000);
server.close();
});
});
describe("port", () => {
it("should be bound", (done) => {
const io = new Server(0);
request(`http://localhost:${getPort(io)}`)
.get("/socket.io/socket.io.js")
.expect(200, successFn(done, io));
});
it("with listen", (done) => {
const io = new Server().listen(0);
request(`http://localhost:${getPort(io)}`)
.get("/socket.io/socket.io.js")
.expect(200, successFn(done, io));
});
});
});

60
test/socket-middleware.ts Normal file
View File

@@ -0,0 +1,60 @@
import { Server } from "..";
import expect from "expect.js";
import { success, createClient } from "./support/util";
describe("socket middleware", () => {
it("should call functions", (done) => {
const io = new Server(0);
const clientSocket = createClient(io, "/", { multiplex: false });
clientSocket.emit("join", "woot");
let run = 0;
io.on("connection", (socket) => {
socket.use((event, next) => {
expect(event).to.eql(["join", "woot"]);
event.unshift("wrap");
run++;
next();
});
socket.use((event, next) => {
expect(event).to.eql(["wrap", "join", "woot"]);
run++;
next();
});
socket.on("wrap", (data1, data2) => {
expect(data1).to.be("join");
expect(data2).to.be("woot");
expect(run).to.be(2);
success(done, io, clientSocket);
});
});
});
it("should pass errors", (done) => {
const io = new Server(0);
const clientSocket = createClient(io, "/", { multiplex: false });
clientSocket.emit("join", "woot");
io.on("connection", (socket) => {
socket.use((event, next) => {
next(new Error("Authentication error"));
});
socket.use((event, next) => {
done(new Error("should not happen"));
});
socket.on("join", () => {
done(new Error("should not happen"));
});
socket.on("error", (err) => {
expect(err).to.be.an(Error);
expect(err.message).to.eql("Authentication error");
success(done, io, clientSocket);
});
});
});
});

View File

@@ -4,6 +4,7 @@ import type { DefaultEventsMap } from "../lib/typed-events";
import { createServer } from "http";
import { expectError, expectType } from "tsd";
import { Adapter } from "socket.io-adapter";
import type { DisconnectReason } from "../lib/socket";
// This file is run by tsd, not mocha.
@@ -17,10 +18,10 @@ describe("server", () => {
sio.on("connection", (s) => {
expectType<Socket<DefaultEventsMap, DefaultEventsMap>>(s);
s.on("disconnect", (reason) => {
expectType<string>(reason);
expectType<DisconnectReason>(reason);
});
s.on("disconnecting", (reason) => {
expectType<string>(reason);
expectType<DisconnectReason>(reason);
});
});
sio.on("connect", (s) => {
@@ -208,6 +209,10 @@ describe("server", () => {
const srv = createServer();
const sio = new Server<ClientToServerEvents, ServerToClientEvents>(srv);
srv.listen(() => {
sio.emit("helloFromServer", "hi", 1);
sio.to("room").emit("helloFromServer", "hi", 1);
sio.timeout(1000).emit("helloFromServer", "hi", 1);
sio.on("connection", (s) => {
s.emit("helloFromServer", "hi", 10);
done();
@@ -219,6 +224,10 @@ describe("server", () => {
const srv = createServer();
const sio = new Server<ClientToServerEvents, ServerToClientEvents>(srv);
srv.listen(() => {
expectError(sio.emit("helloFromClient"));
expectError(sio.to("room").emit("helloFromClient"));
expectError(sio.timeout(1000).to("room").emit("helloFromClient"));
sio.on("connection", (s) => {
expectError(s.emit("helloFromClient", "hi"));
expectError(s.emit("helloFromServer", "hi", 10, "10"));
@@ -233,7 +242,7 @@ describe("server", () => {
});
});
describe("listen and emit event maps", () => {
describe("listen and emit event maps for the serverSideEmit method", () => {
interface ClientToServerEvents {
helloFromClient: (message: string) => void;
}

File diff suppressed because it is too large Load Diff

1043
test/socket.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -31,16 +31,50 @@ expect.Assertion.prototype.contain = function (...args) {
export function createClient(
io: Server,
nsp: string,
opts?: ManagerOptions & SocketOptions
nsp: string = "/",
opts?: Partial<ManagerOptions & SocketOptions>
): ClientSocket {
// @ts-ignore
const port = io.httpServer.address().port;
return ioc(`http://localhost:${port}${nsp}`, opts);
}
export function success(done: Function, io: Server, client: ClientSocket) {
export function success(
done: Function,
io: Server,
...clients: ClientSocket[]
) {
io.close();
client.disconnect();
clients.forEach((client) => client.disconnect());
done();
}
export function successFn(
done: () => void,
sio: Server,
...clientSockets: ClientSocket[]
) {
return () => success(done, sio, ...clientSockets);
}
export function getPort(io: Server): number {
// @ts-ignore
return io.httpServer.address().port;
}
export function createPartialDone(count: number, done: (err?: Error) => void) {
let i = 0;
return () => {
if (++i === count) {
done();
} else if (i > count) {
done(new Error(`partialDone() called too many times: ${i} > ${count}`));
}
};
}
export function waitFor(emitter, event) {
return new Promise((resolve) => {
emitter.once(event, resolve);
});
}

View File

@@ -6,26 +6,10 @@ import expect from "expect.js";
import type { AddressInfo } from "net";
import "./support/util";
import { createPartialDone } from "./support/util";
const SOCKETS_COUNT = 3;
const createPartialDone = (
count: number,
done: () => void,
callback?: () => void
) => {
let i = 0;
return () => {
i++;
if (i === count) {
done();
if (callback) {
callback();
}
}
};
};
class DummyAdapter extends Adapter {
fetchSockets(opts: BroadcastOptions): Promise<any[]> {
return Promise.resolve([
@@ -49,7 +33,7 @@ class DummyAdapter extends Adapter {
}
}
describe("socket.io", () => {
describe("utility methods", () => {
let io: Server, clientSockets: ClientSocket[], serverSockets: Socket[];
beforeEach((done) => {
const srv = createServer();
@@ -59,7 +43,12 @@ describe("socket.io", () => {
clientSockets = [];
for (let i = 0; i < SOCKETS_COUNT; i++) {
clientSockets.push(ioc(`http://localhost:${port}`));
clientSockets.push(
ioc(`http://localhost:${port}`, {
// FIXME needed so that clients are properly closed
transports: ["websocket"],
})
);
}
serverSockets = [];
@@ -77,100 +66,99 @@ describe("socket.io", () => {
clientSockets.forEach((socket) => socket.disconnect());
});
describe("utility methods", () => {
describe("fetchSockets", () => {
it("returns all socket instances", async () => {
const sockets = await io.fetchSockets();
expect(sockets.length).to.eql(3);
});
describe("fetchSockets", () => {
it("returns all socket instances", async () => {
const sockets = await io.fetchSockets();
expect(sockets.length).to.eql(3);
});
it("returns all socket instances in the given room", async () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
const sockets = await io.in("room1").fetchSockets();
expect(sockets.length).to.eql(2);
});
it("returns all socket instances in the given room", async () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
const sockets = await io.in("room1").fetchSockets();
expect(sockets.length).to.eql(2);
});
it("works with a custom adapter", async () => {
io.adapter(DummyAdapter);
const sockets = await io.fetchSockets();
expect(sockets.length).to.eql(1);
const remoteSocket = sockets[0];
expect(remoteSocket.id).to.eql("42");
expect(remoteSocket.rooms).to.contain("42", "room1");
expect(remoteSocket.data).to.eql({ username: "john" });
it("works with a custom adapter", async () => {
io.adapter(DummyAdapter);
const sockets = await io.fetchSockets();
expect(sockets.length).to.eql(1);
const remoteSocket = sockets[0];
expect(remoteSocket.id).to.eql("42");
expect(remoteSocket.rooms).to.contain("42", "room1");
expect(remoteSocket.data).to.eql({ username: "john" });
});
});
describe("socketsJoin", () => {
it("makes all socket instances join the given room", () => {
io.socketsJoin("room1");
serverSockets.forEach((socket) => {
expect(socket.rooms).to.contain("room1");
});
});
describe("socketsJoin", () => {
it("makes all socket instances join the given room", () => {
io.socketsJoin("room1");
serverSockets.forEach((socket) => {
expect(socket.rooms).to.contain("room1");
});
});
it("makes all socket instances in a room join the given room", () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.in("room1").socketsJoin("room3");
expect(serverSockets[0].rooms).to.contain("room3");
expect(serverSockets[1].rooms).to.contain("room3");
expect(serverSockets[2].rooms).to.not.contain("room3");
});
});
it("makes all socket instances in a room join the given room", () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.in("room1").socketsJoin("room3");
expect(serverSockets[0].rooms).to.contain("room3");
expect(serverSockets[1].rooms).to.contain("room3");
expect(serverSockets[2].rooms).to.not.contain("room3");
});
describe("socketsLeave", () => {
it("makes all socket instances leave the given room", () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.socketsLeave("room1");
expect(serverSockets[0].rooms).to.contain("room2");
expect(serverSockets[0].rooms).to.not.contain("room1");
expect(serverSockets[1].rooms).to.not.contain("room1");
});
describe("socketsLeave", () => {
it("makes all socket instances leave the given room", () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.socketsLeave("room1");
expect(serverSockets[0].rooms).to.contain("room2");
expect(serverSockets[0].rooms).to.not.contain("room1");
expect(serverSockets[1].rooms).to.not.contain("room1");
});
it("makes all socket instances in a room leave the given room", () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.in("room2").socketsLeave("room1");
expect(serverSockets[0].rooms).to.contain("room2");
expect(serverSockets[0].rooms).to.not.contain("room1");
expect(serverSockets[1].rooms).to.contain("room1");
});
});
it("makes all socket instances in a room leave the given room", () => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.in("room2").socketsLeave("room1");
expect(serverSockets[0].rooms).to.contain("room2");
expect(serverSockets[0].rooms).to.not.contain("room1");
expect(serverSockets[1].rooms).to.contain("room1");
});
describe("disconnectSockets", () => {
it("makes all socket instances disconnect", (done) => {
io.disconnectSockets(true);
const partialDone = createPartialDone(3, done);
clientSockets[0].on("disconnect", partialDone);
clientSockets[1].on("disconnect", partialDone);
clientSockets[2].on("disconnect", partialDone);
});
describe("disconnectSockets", () => {
it("makes all socket instances disconnect", (done) => {
io.disconnectSockets(true);
it("makes all socket instances in a room disconnect", (done) => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.in("room2").disconnectSockets(true);
const partialDone = createPartialDone(3, done);
clientSockets[0].on("disconnect", partialDone);
clientSockets[1].on("disconnect", partialDone);
clientSockets[2].on("disconnect", partialDone);
const partialDone = createPartialDone(2, () => {
clientSockets[1].off("disconnect");
done();
});
it("makes all socket instances in a room disconnect", (done) => {
serverSockets[0].join(["room1", "room2"]);
serverSockets[1].join("room1");
serverSockets[2].join("room2");
io.in("room2").disconnectSockets(true);
const partialDone = createPartialDone(2, done, () => {
clientSockets[1].off("disconnect");
});
clientSockets[0].on("disconnect", partialDone);
clientSockets[1].on("disconnect", () => {
done(new Error("should not happen"));
});
clientSockets[2].on("disconnect", partialDone);
clientSockets[0].on("disconnect", partialDone);
clientSockets[1].on("disconnect", () => {
done(new Error("should not happen"));
});
clientSockets[2].on("disconnect", partialDone);
});
});
});

View File

@@ -1,4 +1,8 @@
import { App, us_socket_local_port } from "uWebSockets.js";
import {
App,
us_socket_local_port,
us_listen_socket_close,
} from "uWebSockets.js";
import { Server } from "..";
import { io as ioc, Socket as ClientSocket } from "socket.io-client";
import request from "supertest";
@@ -19,6 +23,7 @@ const shouldNotHappen = (done) => () => done(new Error("should not happen"));
describe("socket.io with uWebSocket.js-based engine", () => {
let io: Server,
uwsSocket: any,
port: number,
client: ClientSocket,
clientWSOnly: ClientSocket,
@@ -33,6 +38,7 @@ describe("socket.io with uWebSocket.js-based engine", () => {
io.of("/custom");
app.listen(0, (listenSocket) => {
uwsSocket = listenSocket;
port = us_socket_local_port(listenSocket);
client = ioc(`http://localhost:${port}`);
@@ -54,6 +60,8 @@ describe("socket.io with uWebSocket.js-based engine", () => {
afterEach(() => {
io.close();
us_listen_socket_close(uwsSocket);
client.disconnect();
clientWSOnly.disconnect();
clientPollingOnly.disconnect();
@@ -178,6 +186,12 @@ describe("socket.io with uWebSocket.js-based engine", () => {
io.to("room1").emit("hello");
});
it("should not crash when socket is disconnected before the upgrade", (done) => {
client.on("disconnect", () => done());
io.of("/").sockets.get(client.id)!.disconnect();
});
it("should serve static files", (done) => {
const clientVersion = require("socket.io-client/package.json").version;

64
test/v2-compatibility.ts Normal file
View File

@@ -0,0 +1,64 @@
import { Server, Socket } from "..";
import expect from "expect.js";
import { success, getPort, waitFor } from "./support/util";
import * as io_v2 from "socket.io-client-v2";
describe("v2 compatibility", () => {
it("should connect if `allowEIO3` is true", (done) => {
const io = new Server(0, {
allowEIO3: true,
});
const clientSocket = io_v2.connect(`http://localhost:${getPort(io)}`, {
multiplex: false,
});
Promise.all([
waitFor(io, "connection"),
waitFor(clientSocket, "connect"),
]).then(([socket]) => {
expect((socket as Socket).id).to.eql(clientSocket.id);
success(done, io, clientSocket);
});
});
it("should be able to connect to a namespace with a query", (done) => {
const io = new Server(0, {
allowEIO3: true,
});
const clientSocket = io_v2.connect(
`http://localhost:${getPort(io)}/the-namespace`,
{
multiplex: false,
}
);
clientSocket.query = { test: "123" };
Promise.all([
waitFor(io.of("/the-namespace"), "connection"),
waitFor(clientSocket, "connect"),
]).then(([socket]) => {
expect((socket as Socket).handshake.auth).to.eql({ test: "123" });
success(done, io, clientSocket);
});
});
it("should not connect if `allowEIO3` is false (default)", (done) => {
const io = new Server(0);
const clientSocket = io_v2.connect(`http://localhost:${getPort(io)}`, {
multiplex: false,
});
clientSocket.on("connect", () => {
done(new Error("should not happen"));
});
clientSocket.on("connect_error", () => {
success(done, io, clientSocket);
});
});
});