[
  {
    "path": "README.md",
    "content": "# Engine.IO Protocol\n\nThis document describes the 4th version of the Engine.IO protocol.\n\n**Table of content**\n\n- [Introduction](#introduction)\n- [Transports](#transports)\n  - [HTTP long-polling](#http-long-polling)\n    - [Request path](#request-path)\n    - [Query parameters](#query-parameters)\n    - [Headers](#headers)\n    - [Sending and receiving data](#sending-and-receiving-data)\n      - [Sending data](#sending-data)\n      - [Receiving data](#receiving-data)\n  - [WebSocket](#websocket)\n- [Protocol](#protocol)\n  - [Handshake](#handshake)\n  - [Heartbeat](#heartbeat)\n  - [Upgrade](#upgrade)\n  - [Message](#message)\n- [Packet encoding](#packet-encoding)\n  - [HTTP long-polling](#http-long-polling-1)\n  - [WebSocket](#websocket-1)\n- [History](#history)\n  - [From v2 to v3](#from-v2-to-v3)\n  - [From v3 to v4](#from-v3-to-v4)\n- [Test suite](#test-suite)\n\n\n\n## Introduction\n\nThe Engine.IO protocol enables [full-duplex](https://en.wikipedia.org/wiki/Duplex_(telecommunications)#FULL-DUPLEX) and low-overhead communication between a client and a server.\n\nIt is based on the [WebSocket protocol](https://en.wikipedia.org/wiki/WebSocket) and uses [HTTP long-polling](https://en.wikipedia.org/wiki/Push_technology#Long_polling) as fallback if the WebSocket connection can't be established.\n\nThe reference implementation is written in [TypeScript](https://www.typescriptlang.org/):\n\n- server: https://github.com/socketio/engine.io\n- client: https://github.com/socketio/engine.io-client\n\nThe [Socket.IO protocol](https://github.com/socketio/socket.io-protocol) is built on top of these foundations, bringing additional features over the communication channel provided by the Engine.IO protocol.\n\n## Transports\n\nThe connection between an Engine.IO client and an Engine.IO server can be established with:\n\n- [HTTP long-polling](#http-long-polling)\n- [WebSocket](#websocket)\n\n### HTTP long-polling\n\nThe HTTP long-polling transport (also simply referred as \"polling\") consists of successive HTTP requests:\n\n- long-running `GET` requests, for receiving data from the server\n- short-running `POST` requests, for sending data to the server\n\n#### Request path\n\nThe path of the HTTP requests is `/engine.io/` by default.\n\nIt might be updated by libraries built on top of the protocol (for example, the Socket.IO protocol uses `/socket.io/`).\n\n#### Query parameters\n\nThe following query parameters are used:\n\n| Name        | Value     | Description                                                        |\n|-------------|-----------|--------------------------------------------------------------------|\n| `EIO`       | `4`       | Mandatory, the version of the protocol.                            | \n| `transport` | `polling` | Mandatory, the name of the transport.                              |\n| `sid`       | `<sid>`   | Mandatory once the session is established, the session identifier. |\n\nIf a mandatory query parameter is missing, then the server MUST respond with an HTTP 400 error status.\n\n#### Headers\n\nWhen sending binary data, the sender (client or server) MUST include a `Content-Type: application/octet-stream` header.\n\nWithout an explicit `Content-Type` header, the receiver SHOULD infer that the data is plaintext.\n\nReference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type\n\n#### Sending and receiving data\n\n##### Sending data\n\nTo send some packets, a client MUST create an HTTP `POST` request with the packets encoded in the request body:\n\n```\nCLIENT                                                 SERVER\n\n  │                                                      │\n  │   POST /engine.io/?EIO=4&transport=polling&sid=...   │\n  │ ───────────────────────────────────────────────────► │\n  │ ◄──────────────────────────────────────────────────┘ │\n  │                        HTTP 200                      │\n  │                                                      │\n```\n\nThe server MUST return an HTTP 400 response if the session ID (from the `sid` query parameter) is not known.\n\nTo indicate success, the server MUST return an HTTP 200 response, with the string `ok` in the response body.\n\nTo ensure packet ordering, a client MUST NOT have more than one active `POST` request. Should it happen, the server MUST return an HTTP 400 error status and close the session.\n\n##### Receiving data\n\nTo receive some packets, a client MUST create an HTTP `GET` request:\n\n```\nCLIENT                                                SERVER\n\n  │   GET /engine.io/?EIO=4&transport=polling&sid=...   │\n  │ ──────────────────────────────────────────────────► │\n  │                                                   . │\n  │                                                   . │\n  │                                                   . │\n  │                                                   . │\n  │ ◄─────────────────────────────────────────────────┘ │\n  │                       HTTP 200                      │\n```\n\nThe server MUST return an HTTP 400 response if the session ID (from the `sid` query parameter) is not known.\n\nThe server MAY not respond right away if there are no packets buffered for the given session. Once there are some packets to be sent, the server SHOULD encode them (see [Packet encoding](#packet-encoding)) and send them in the response body of the HTTP request.\n\nTo ensure packet ordering, a client MUST NOT have more than one active `GET` request. Should it happen, the server MUST return an HTTP 400 error status and close the session.\n\n### WebSocket\n\nThe WebSocket transport consists of a [WebSocket connection](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), which provides a bidirectional and low-latency communication channel between the server and the client.\n\nThe following query parameters are used:\n\n| Name        | Value       | Description                                                                   |\n|-------------|-------------|-------------------------------------------------------------------------------|\n| `EIO`       | `4`         | Mandatory, the version of the protocol.                                       | \n| `transport` | `websocket` | Mandatory, the name of the transport.                                         |\n| `sid`       | `<sid>`     | Optional, depending on whether it's an upgrade from HTTP long-polling or not. |\n\nIf a mandatory query parameter is missing, then the server MUST close the WebSocket connection.\n\nEach packet (read or write) is sent its own [WebSocket frame](https://datatracker.ietf.org/doc/html/rfc6455#section-5).\n\nA client MUST NOT open more than one WebSocket connection per session. Should it happen, the server MUST close the WebSocket connection.\n\n## Protocol\n\nAn Engine.IO packet consists of:\n\n- a packet type\n- an optional packet payload\n\nHere is the list of available packet types:\n\n| Type    | ID  | Usage                                            |\n|---------|-----|--------------------------------------------------|\n| open    | 0   | Used during the [handshake](#handshake).         | \n| close   | 1   | Used to indicate that a transport can be closed. |\n| ping    | 2   | Used in the [heartbeat mechanism](#heartbeat).   |\n| pong    | 3   | Used in the [heartbeat mechanism](#heartbeat).   |\n| message | 4   | Used to send a payload to the other side.        |\n| upgrade | 5   | Used during the [upgrade process](#upgrade).     |\n| noop    | 6   | Used during the [upgrade process](#upgrade).     |\n\n### Handshake\n\nTo establish a connection, the client MUST send an HTTP `GET` request to the server:\n\n- HTTP long-polling first (by default)\n\n```\nCLIENT                                                    SERVER\n\n  │                                                          │\n  │        GET /engine.io/?EIO=4&transport=polling           │\n  │ ───────────────────────────────────────────────────────► │\n  │ ◄──────────────────────────────────────────────────────┘ │\n  │                        HTTP 200                          │\n  │                                                          │\n```\n\n- WebSocket-only session\n\n```\nCLIENT                                                    SERVER\n\n  │                                                          │\n  │        GET /engine.io/?EIO=4&transport=websocket         │\n  │ ───────────────────────────────────────────────────────► │\n  │ ◄──────────────────────────────────────────────────────┘ │\n  │                        HTTP 101                          │\n  │                                                          │\n```\n\nIf the server accepts the connection, then it MUST respond with an `open` packet with the following JSON-encoded payload:\n\n| Key            | Type       | Description                                                                                                       |\n|----------------|------------|-------------------------------------------------------------------------------------------------------------------|\n| `sid`          | `string`   | The session ID.                                                                                                   |\n| `upgrades`     | `string[]` | The list of available [transport upgrades](#upgrade).                                                             |\n| `pingInterval` | `number`   | The ping interval, used in the [heartbeat mechanism](#heartbeat) (in milliseconds).                               |\n| `pingTimeout`  | `number`   | The ping timeout, used in the [heartbeat mechanism](#heartbeat) (in milliseconds).                                |\n| `maxPayload`   | `number`   | The maximum number of bytes per chunk, used by the client to aggregate packets into [payloads](#packet-encoding). |\n\nExample:\n\n```json\n{\n  \"sid\": \"lv_VI97HAXpY6yYWAAAC\",\n  \"upgrades\": [\"websocket\"],\n  \"pingInterval\": 25000,\n  \"pingTimeout\": 20000,\n  \"maxPayload\": 1000000\n}\n```\n\nThe client MUST send the `sid` value in the query parameters of all subsequent requests.\n\n### Heartbeat\n\nOnce the [handshake](#handshake) is completed, a heartbeat mechanism is started to check the liveness of the connection:\n\n```\nCLIENT                                                 SERVER\n\n  │                   *** Handshake ***                  │\n  │                                                      │\n  │  ◄─────────────────────────────────────────────────  │\n  │                           2                          │  (ping packet)\n  │  ─────────────────────────────────────────────────►  │\n  │                           3                          │  (pong packet)\n```\n\nAt a given interval (the `pingInterval` value sent in the handshake) the server sends a `ping` packet and the client has a few seconds (the `pingTimeout` value) to send a `pong` packet back.\n\nIf the server does not receive a `pong` packet back, then it SHOULD consider that the connection is closed.\n\nConversely, if the client does not receive a `ping` packet within `pingInterval + pingTimeout`, then it SHOULD consider that the connection is closed.\n\n### Upgrade\n\nBy default, the client SHOULD create an HTTP long-polling connection, and then upgrade to better transports if available.\n\nTo upgrade to WebSocket, the client MUST:\n\n- pause the HTTP long-polling transport (no more HTTP request gets sent), to ensure that no packet gets lost\n- open a WebSocket connection with the same session ID\n- send a `ping` packet with the string `probe` in the payload\n\nThe server MUST:\n\n- send a `noop` packet to any pending `GET` request (if applicable) to cleanly close HTTP long-polling transport\n- respond with a `pong` packet with the string `probe` in the payload\n\nFinally, the client MUST send a `upgrade` packet to complete the upgrade:\n\n```\nCLIENT                                                 SERVER\n\n  │                                                      │\n  │   GET /engine.io/?EIO=4&transport=websocket&sid=...  │\n  │ ───────────────────────────────────────────────────► │\n  │  ◄─────────────────────────────────────────────────┘ │\n  │            HTTP 101 (WebSocket handshake)            │\n  │                                                      │\n  │            -----  WebSocket frames -----             │\n  │  ─────────────────────────────────────────────────►  │\n  │                         2probe                       │ (ping packet)\n  │  ◄─────────────────────────────────────────────────  │\n  │                         3probe                       │ (pong packet)\n  │  ─────────────────────────────────────────────────►  │\n  │                         5                            │ (upgrade packet)\n  │                                                      │\n```\n\n### Message\n\nOnce the [handshake](#handshake) is completed, the client and the server can exchange data by including it in a `message` packet.\n\n\n## Packet encoding\n\nThe serialization of an Engine.IO packet depends on the type of the payload (plaintext or binary) and on the transport.\n\nThe character encoding is UTF-8 for plain text and for base64-encoded binary payloads.\n\n### HTTP long-polling\n\nDue to the nature of the HTTP long-polling transport, multiple packets might be concatenated in a single payload in order to increase throughput.\n\nFormat:\n\n```\n<packet type>[<data>]<separator><packet type>[<data>]<separator><packet type>[<data>][...]\n```\n\nExample:\n\n```\n4hello\\x1e2\\x1e4world\n\nwith:\n\n4      => message packet type\nhello  => message payload\n\\x1e   => separator\n2      => ping packet type\n\\x1e   => separator\n4      => message packet type\nworld  => message payload\n```\n\nThe packets are separated by the [record separator character](https://en.wikipedia.org/wiki/C0_and_C1_control_codes#Field_separators): `\\x1e`\n\nBinary payloads MUST be base64-encoded and prefixed with a `b` character:\n\nExample:\n\n```\n4hello\\x1ebAQIDBA==\n\nwith:\n\n4         => message packet type\nhello     => message payload\n\\x1e      => separator\nb         => binary prefix\nAQIDBA==  => buffer <01 02 03 04> encoded as base64\n```\n\nThe client SHOULD use the `maxPayload` value sent during the [handshake](#handshake) to decide how many packets should be concatenated.\n\n### WebSocket\n\nEach Engine.IO packet is sent in its own [WebSocket frame](https://datatracker.ietf.org/doc/html/rfc6455#section-5).\n\nFormat:\n\n```\n<packet type>[<data>]\n```\n\nExample:\n\n```\n4hello\n\nwith:\n\n4      => message packet type\nhello  => message payload (UTF-8 encoded)\n```\n\nBinary payloads are sent as is, without modification.\n\n## History\n\n### From v2 to v3\n\n- add support for binary data\n\nThe [2nd version](https://github.com/socketio/engine.io-protocol/tree/v2) of the protocol is used in Socket.IO `v0.9` and below.\n\nThe [3rd version](https://github.com/socketio/engine.io-protocol/tree/v3) of the protocol is used in Socket.IO `v1` and `v2`.\n\n### From v3 to v4\n\n- reverse ping/pong mechanism\n\nThe ping packets are now sent by the server, because the timers set in the browsers are not reliable enough. We\nsuspect that a lot of timeout problems came from timers being delayed on the client-side.\n\n- always use base64 when encoding a payload with binary data\n\nThis change allows to treat all payloads (with or without binary) the same way, without having to take in account\nwhether the client or the current transport supports binary data or not.\n\nPlease note that this only applies to HTTP long-polling. Binary data is sent in WebSocket frames with no additional transformation.\n\n- use a record separator (`\\x1e`) instead of counting of characters\n\nCounting characters prevented (or at least makes harder) to implement the protocol in other languages, which may not use\nthe UTF-16 encoding.\n\nFor example, `€` was encoded to `2:4€`, though `Buffer.byteLength('€') === 3`.\n\nNote: this assumes the record separator is not used in the data.\n\nThe 4th version (current) is included in Socket.IO `v3` and above.\n\n## Test suite\n\nThe test suite in the `test-suite/` directory lets you check the compliance of a server implementation.\n\nUsage:\n\n- in Node.js: `npm ci && npm test`\n- in a browser: simply open the `index.html` file in your browser\n\nFor reference, here is expected configuration for the JavaScript server to pass all tests:\n\n```js\nimport { listen } from \"engine.io\";\n\nconst server = listen(3000, {\n  pingInterval: 300,\n  pingTimeout: 200,\n  maxPayload: 1e6,\n  cors: {\n    origin: \"*\"\n  }\n});\n\nserver.on(\"connection\", socket => {\n  socket.on(\"data\", (...args) => {\n    socket.send(...args);\n  });\n});\n```\n"
  },
  {
    "path": "test-suite/.gitignore",
    "content": "node_modules\n"
  },
  {
    "path": "test-suite/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"utf-8\" />\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n\n  <title>Test suite for the Engine.IO protocol</title>\n  <link rel=\"stylesheet\" href=\"https://unpkg.com/mocha@9/mocha.css\" />\n</head>\n<body>\n\n<div id=\"mocha\"></div>\n\n<script src=\"https://unpkg.com/mocha@9/mocha.js\"></script>\n<script src=\"https://unpkg.com/chai@4/chai.js\" ></script>\n<script src=\"https://unpkg.com/chai-string@1/chai-string.js\" ></script>\n\n<script class=\"mocha-init\">\n  mocha.setup(\"bdd\");\n  mocha.checkLeaks();\n</script>\n\n<script type=\"module\" src=\"test-suite.js\"></script>\n\n<script class=\"mocha-exec\">\n  mocha.run();\n</script>\n\n</body>\n</html>\n"
  },
  {
    "path": "test-suite/node-imports.js",
    "content": "import fetch from \"node-fetch\";\nimport { WebSocket } from \"ws\";\nimport chai from \"chai\";\nimport chaiString from \"chai-string\";\n\nchai.use(chaiString);\n\nglobalThis.fetch = fetch;\nglobalThis.WebSocket = WebSocket;\nglobalThis.chai = chai;\n"
  },
  {
    "path": "test-suite/package.json",
    "content": "{\n  \"name\": \"engine.io-protocol-test-suite\",\n  \"version\": \"0.0.1\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"scripts\": {\n    \"format\": \"prettier -w *.js\",\n    \"test\": \"mocha test-suite.js\"\n  },\n  \"devDependencies\": {\n    \"chai\": \"^4.3.6\",\n    \"chai-string\": \"^1.5.0\",\n    \"mocha\": \"^9.2.1\",\n    \"node-fetch\": \"^3.2.0\",\n    \"prettier\": \"^2.5.1\",\n    \"ws\": \"^8.5.0\"\n  }\n}\n"
  },
  {
    "path": "test-suite/test-suite.js",
    "content": "const isNodejs = typeof window === \"undefined\";\n\nif (isNodejs) {\n  // make the tests runnable in both the browser and Node.js\n  await import(\"./node-imports.js\");\n}\n\nconst { expect } = chai;\n\nconst URL = \"http://localhost:3000\";\nconst WS_URL = URL.replace(\"http\", \"ws\");\n\nconst PING_INTERVAL = 300;\nconst PING_TIMEOUT = 200;\n\nfunction sleep(delay) {\n  return new Promise((resolve) => setTimeout(resolve, delay));\n}\n\nfunction waitFor(socket, eventType) {\n  return new Promise((resolve) => {\n    socket.addEventListener(\n      eventType,\n      (event) => {\n        resolve(event);\n      },\n      { once: true }\n    );\n  });\n}\n\nasync function initLongPollingSession() {\n  const response = await fetch(`${URL}/engine.io/?EIO=4&transport=polling`);\n  const content = await response.text();\n  return JSON.parse(content.substring(1)).sid;\n}\n\ndescribe(\"Engine.IO protocol\", () => {\n  describe(\"handshake\", () => {\n    describe(\"HTTP long-polling\", () => {\n      it(\"successfully opens a session\", async () => {\n        const response = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling`\n        );\n\n        expect(response.status).to.eql(200);\n\n        const content = await response.text();\n\n        expect(content).to.startsWith(\"0\");\n\n        const value = JSON.parse(content.substring(1));\n\n        expect(value).to.have.all.keys(\n          \"sid\",\n          \"upgrades\",\n          \"pingInterval\",\n          \"pingTimeout\",\n          \"maxPayload\"\n        );\n        expect(value.sid).to.be.a(\"string\");\n        expect(value.upgrades).to.eql([\"websocket\"]);\n        expect(value.pingInterval).to.eql(PING_INTERVAL);\n        expect(value.pingTimeout).to.eql(PING_TIMEOUT);\n        expect(value.maxPayload).to.eql(1000000);\n      });\n\n      it(\"fails with an invalid 'EIO' query parameter\", async () => {\n        const response = await fetch(`${URL}/engine.io/?transport=polling`);\n\n        expect(response.status).to.eql(400);\n\n        const response2 = await fetch(\n          `${URL}/engine.io/?EIO=abc&transport=polling`\n        );\n\n        expect(response2.status).to.eql(400);\n      });\n\n      it(\"fails with an invalid 'transport' query parameter\", async () => {\n        const response = await fetch(`${URL}/engine.io/?EIO=4`);\n\n        expect(response.status).to.eql(400);\n\n        const response2 = await fetch(`${URL}/engine.io/?EIO=4&transport=abc`);\n\n        expect(response2.status).to.eql(400);\n      });\n\n      it(\"fails with an invalid request method\", async () => {\n        const response = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling`,\n          {\n            method: \"post\",\n          }\n        );\n\n        expect(response.status).to.eql(400);\n\n        const response2 = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling`,\n          {\n            method: \"put\",\n          }\n        );\n\n        expect(response2.status).to.eql(400);\n      });\n    });\n\n    describe(\"WebSocket\", () => {\n      it(\"successfully opens a session\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n\n        const { data } = await waitFor(socket, \"message\");\n\n        expect(data).to.startsWith(\"0\");\n\n        const value = JSON.parse(data.substring(1));\n\n        expect(value).to.have.all.keys(\n          \"sid\",\n          \"upgrades\",\n          \"pingInterval\",\n          \"pingTimeout\",\n          \"maxPayload\"\n        );\n        expect(value.sid).to.be.a(\"string\");\n        expect(value.upgrades).to.eql([]);\n        expect(value.pingInterval).to.eql(PING_INTERVAL);\n        expect(value.pingTimeout).to.eql(PING_TIMEOUT);\n        expect(value.maxPayload).to.eql(1000000);\n\n        socket.close();\n      });\n\n      it(\"fails with an invalid 'EIO' query parameter\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?transport=websocket`\n        );\n\n        if (isNodejs) {\n          socket.on(\"error\", () => {});\n        }\n\n        waitFor(socket, \"close\");\n\n        const socket2 = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=abc&transport=websocket`\n        );\n\n        if (isNodejs) {\n          socket2.on(\"error\", () => {});\n        }\n\n        waitFor(socket2, \"close\");\n      });\n\n      it(\"fails with an invalid 'transport' query parameter\", async () => {\n        const socket = new WebSocket(`${WS_URL}/engine.io/?EIO=4`);\n\n        if (isNodejs) {\n          socket.on(\"error\", () => {});\n        }\n\n        waitFor(socket, \"close\");\n\n        const socket2 = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=abc`\n        );\n\n        if (isNodejs) {\n          socket2.on(\"error\", () => {});\n        }\n\n        waitFor(socket2, \"close\");\n      });\n    });\n  });\n\n  describe(\"message\", () => {\n    describe(\"HTTP long-polling\", () => {\n      it(\"sends and receives a payload containing one plain text packet\", async () => {\n        const sid = await initLongPollingSession();\n\n        const pushResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`,\n          {\n            method: \"post\",\n            body: \"4hello\",\n          }\n        );\n\n        expect(pushResponse.status).to.eql(200);\n\n        const postContent = await pushResponse.text();\n\n        expect(postContent).to.eql(\"ok\");\n\n        const pollResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse.status).to.eql(200);\n\n        const pollContent = await pollResponse.text();\n\n        expect(pollContent).to.eql(\"4hello\");\n      });\n\n      it(\"sends and receives a payload containing several plain text packets\", async () => {\n        const sid = await initLongPollingSession();\n\n        const pushResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`,\n          {\n            method: \"post\",\n            body: \"4test1\\x1e4test2\\x1e4test3\",\n          }\n        );\n\n        expect(pushResponse.status).to.eql(200);\n\n        const postContent = await pushResponse.text();\n\n        expect(postContent).to.eql(\"ok\");\n\n        const pollResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse.status).to.eql(200);\n\n        const pollContent = await pollResponse.text();\n\n        expect(pollContent).to.eql(\"4test1\\x1e4test2\\x1e4test3\");\n      });\n\n      it(\"sends and receives a payload containing plain text and binary packets\", async () => {\n        const sid = await initLongPollingSession();\n\n        const pushResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`,\n          {\n            method: \"post\",\n            body: \"4hello\\x1ebAQIDBA==\",\n          }\n        );\n\n        expect(pushResponse.status).to.eql(200);\n\n        const postContent = await pushResponse.text();\n\n        expect(postContent).to.eql(\"ok\");\n\n        const pollResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse.status).to.eql(200);\n\n        const pollContent = await pollResponse.text();\n\n        expect(pollContent).to.eql(\"4hello\\x1ebAQIDBA==\");\n      });\n\n      it(\"closes the session upon invalid packet format\", async () => {\n        const sid = await initLongPollingSession();\n\n        try {\n          const pushResponse = await fetch(\n            `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`,\n            {\n              method: \"post\",\n              body: \"abc\",\n            }\n          );\n\n          expect(pushResponse.status).to.eql(400);\n        } catch (e) {\n          // node-fetch throws when the request is closed abnormally\n        }\n\n        const pollResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse.status).to.eql(400);\n      });\n\n      it(\"closes the session upon duplicate poll requests\", async () => {\n        const sid = await initLongPollingSession();\n\n        const pollResponses = await Promise.all([\n          fetch(`${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`),\n          sleep(5).then(() => fetch(`${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}&t=burst`)),\n        ]);\n\n        expect(pollResponses[0].status).to.eql(200);\n\n        const content = await pollResponses[0].text();\n\n        expect(content).to.eql(\"1\");\n\n        // the Node.js implementation uses HTTP 500 (Internal Server Error), but HTTP 400 seems more suitable\n        expect(pollResponses[1].status).to.be.oneOf([400, 500]);\n\n        const pollResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse.status).to.eql(400);\n      });\n    });\n\n    describe(\"WebSocket\", () => {\n      it(\"sends and receives a plain text packet\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n\n        await waitFor(socket, \"open\");\n\n        await waitFor(socket, \"message\"); // handshake\n\n        socket.send(\"4hello\");\n\n        const { data } = await waitFor(socket, \"message\");\n\n        expect(data).to.eql(\"4hello\");\n\n        socket.close();\n      });\n\n      it(\"sends and receives a binary packet\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n        socket.binaryType = \"arraybuffer\";\n\n        await waitFor(socket, \"message\"); // handshake\n\n        socket.send(Uint8Array.from([1, 2, 3, 4]));\n\n        const { data } = await waitFor(socket, \"message\");\n\n        expect(data).to.eql(Uint8Array.from([1, 2, 3, 4]).buffer);\n\n        socket.close();\n      });\n\n      it(\"closes the session upon invalid packet format\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n\n        await waitFor(socket, \"message\"); // handshake\n\n        socket.send(\"abc\");\n\n        await waitFor(socket, \"close\");\n\n        socket.close();\n      });\n    });\n  });\n\n  describe(\"heartbeat\", function () {\n    this.timeout(5000);\n\n    describe(\"HTTP long-polling\", () => {\n      it(\"sends ping/pong packets\", async () => {\n        const sid = await initLongPollingSession();\n\n        for (let i = 0; i < 3; i++) {\n          const pollResponse = await fetch(\n            `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n          );\n\n          expect(pollResponse.status).to.eql(200);\n\n          const pollContent = await pollResponse.text();\n\n          expect(pollContent).to.eql(\"2\");\n\n          const pushResponse = await fetch(\n            `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`,\n            {\n              method: \"post\",\n              body: \"3\",\n            }\n          );\n\n          expect(pushResponse.status).to.eql(200);\n        }\n      });\n\n      it(\"closes the session upon ping timeout\", async () => {\n        const sid = await initLongPollingSession();\n\n        await sleep(PING_INTERVAL + PING_TIMEOUT);\n\n        const pollResponse = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse.status).to.eql(400);\n      });\n    });\n\n    describe(\"WebSocket\", () => {\n      it(\"sends ping/pong packets\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n\n        await waitFor(socket, \"message\"); // handshake\n\n        for (let i = 0; i < 3; i++) {\n          const { data } = await waitFor(socket, \"message\");\n\n          expect(data).to.eql(\"2\");\n\n          socket.send(\"3\");\n        }\n\n        socket.close();\n      });\n\n      it(\"closes the session upon ping timeout\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n\n        await waitFor(socket, \"close\"); // handshake\n      });\n    });\n  });\n\n  describe(\"close\", () => {\n    describe(\"HTTP long-polling\", () => {\n      it(\"forcefully closes the session\", async () => {\n        const sid = await initLongPollingSession();\n\n        const [pollResponse] = await Promise.all([\n          fetch(`${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`),\n          fetch(`${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`, {\n            method: \"post\",\n            body: \"1\",\n          }),\n        ]);\n\n        expect(pollResponse.status).to.eql(200);\n\n        const pullContent = await pollResponse.text();\n\n        expect(pullContent).to.eql(\"6\");\n\n        const pollResponse2 = await fetch(\n          `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n        );\n\n        expect(pollResponse2.status).to.eql(400);\n      });\n    });\n\n    describe(\"WebSocket\", () => {\n      it(\"forcefully closes the session\", async () => {\n        const socket = new WebSocket(\n          `${WS_URL}/engine.io/?EIO=4&transport=websocket`\n        );\n\n        await waitFor(socket, \"message\"); // handshake\n\n        socket.send(\"1\");\n\n        await waitFor(socket, \"close\");\n      });\n    });\n  });\n\n  describe(\"upgrade\", () => {\n    it(\"successfully upgrades from HTTP long-polling to WebSocket\", async () => {\n      const sid = await initLongPollingSession();\n\n      const socket = new WebSocket(\n        `${WS_URL}/engine.io/?EIO=4&transport=websocket&sid=${sid}`\n      );\n\n      await waitFor(socket, \"open\");\n\n      // send probe\n      socket.send(\"2probe\");\n\n      const probeResponse = await waitFor(socket, \"message\");\n\n      expect(probeResponse.data).to.eql(\"3probe\");\n\n      const pollResponse = await fetch(\n        `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n      );\n\n      expect(pollResponse.status).to.eql(200);\n\n      const pollContent = await pollResponse.text();\n\n      expect(pollContent).to.eql(\"6\"); // \"noop\" packet to cleanly end the HTTP long-polling request\n\n      // complete upgrade\n      socket.send(\"5\");\n\n      socket.send(\"4hello\");\n\n      const { data } = await waitFor(socket, \"message\");\n\n      expect(data).to.eql(\"4hello\");\n    });\n\n    it(\"ignores HTTP requests with same sid after upgrade\", async () => {\n      const sid = await initLongPollingSession();\n\n      const socket = new WebSocket(\n        `${WS_URL}/engine.io/?EIO=4&transport=websocket&sid=${sid}`\n      );\n\n      await waitFor(socket, \"open\");\n      socket.send(\"2probe\");\n      socket.send(\"5\");\n\n      const pollResponse = await fetch(\n        `${URL}/engine.io/?EIO=4&transport=polling&sid=${sid}`\n      );\n\n      expect(pollResponse.status).to.eql(400);\n\n      socket.send(\"4hello\");\n\n      const { data } = await waitFor(socket, \"message\");\n\n      expect(data).to.eql(\"4hello\");\n    });\n\n    it(\"ignores WebSocket connection with same sid after upgrade\", async () => {\n      const sid = await initLongPollingSession();\n\n      const socket = new WebSocket(\n        `${WS_URL}/engine.io/?EIO=4&transport=websocket&sid=${sid}`\n      );\n\n      await waitFor(socket, \"open\");\n      socket.send(\"2probe\");\n      socket.send(\"5\");\n\n      const socket2 = new WebSocket(\n        `${WS_URL}/engine.io/?EIO=4&transport=websocket&sid=${sid}`\n      );\n\n      await waitFor(socket2, \"close\");\n\n      socket.send(\"4hello\");\n\n      const { data } = await waitFor(socket, \"message\");\n\n      expect(data).to.eql(\"4hello\");\n    });\n  });\n});\n"
  }
]