{"id":13912673,"url":"https://github.com/jjxxs/websocket-ts","last_synced_at":"2025-07-18T12:32:19.895Z","repository":{"id":43486231,"uuid":"294694997","full_name":"jjxxs/websocket-ts","owner":"jjxxs","description":"A WebSocket for browsers with optional auto-reconnect and message buffering written in TypeScript.","archived":false,"fork":false,"pushed_at":"2023-10-08T22:36:57.000Z","size":509,"stargazers_count":116,"open_issues_count":6,"forks_count":20,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-11T18:28:54.341Z","etag":null,"topics":["browser","buffer","client-websocket","reconnecting","typescript","websocket"],"latest_commit_sha":null,"homepage":"https://jjxxs.github.io/websocket-ts/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jjxxs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2020-09-11T12:54:04.000Z","updated_at":"2024-08-29T06:16:16.000Z","dependencies_parsed_at":"2024-01-14T08:49:07.380Z","dependency_job_id":"a5122da6-af42-446d-872b-86a521cc3ef0","html_url":"https://github.com/jjxxs/websocket-ts","commit_stats":{"total_commits":38,"total_committers":2,"mean_commits":19.0,"dds":0.3157894736842105,"last_synced_commit":"0b9673c1799293d08d9de9d0d71c6711c628412b"},"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jjxxs%2Fwebsocket-ts","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jjxxs%2Fwebsocket-ts/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jjxxs%2Fwebsocket-ts/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jjxxs%2Fwebsocket-ts/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jjxxs","download_url":"https://codeload.github.com/jjxxs/websocket-ts/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":226409841,"owners_count":17620717,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["browser","buffer","client-websocket","reconnecting","typescript","websocket"],"created_at":"2024-08-07T01:01:43.394Z","updated_at":"2025-07-18T12:32:19.882Z","avatar_url":"https://github.com/jjxxs.png","language":"TypeScript","funding_links":[],"categories":["typescript"],"sub_categories":[],"readme":"\u003cdiv\u003e\n  \u003cdiv align=\"center\"\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/jjxxs/websocket-ts/gh-pages/websocket-ts-logo.svg\" alt=\"websocket-ts\" width=\"300\" height=\"65\" /\u003e\n  \u003c/div\u003e\n  \u003cp align=\"center\"\u003e\n    \u003cimg src=\"https://github.com/jjxxs/websocket-ts/actions/workflows/build.yml/badge.svg\" alt=\"Build Status\" /\u003e\n    \u003cimg src=\"https://github.com/jjxxs/websocket-ts/actions/workflows/test.yml/badge.svg\" alt=\"Build Status\" /\u003e\n    \u003ca href=\"https://coveralls.io/github/jjxxs/websocket-ts?branch=master\"\u003e\n      \u003cimg src=\"https://coveralls.io/repos/github/jjxxs/websocket-ts/badge.svg?branch=master\u0026service=github\" alt=\"Coverage Status\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/jjxxs/websocket-ts/releases/latest\"\u003e\n      \u003cimg src=\"https://img.shields.io/github/v/release/jjxxs/websocket-ts\" alt=\"Release\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"/LICENSE\"\u003e\n      \u003cimg src=\"https://img.shields.io/github/license/jjxxs/websocket-ts\" alt=\"License\" /\u003e\n    \u003c/a\u003e\n  \u003c/p\u003e\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\nA \u003cb\u003eWebSocket\u003c/b\u003e for browsers with \u003cb\u003eauto-reconnect\u003c/b\u003e and \u003cb\u003emessage buffering\u003c/b\u003e written in \u003cb\u003eTypeScript\u003c/b\u003e.\n\u003c/div\u003e\n\n## Features\n\n- **Lightweight \u0026 Standalone**: No dependencies, 2.1 kB minified \u0026 gzipped.\n- **Browser-native**: Utilizes WebSocket API, offers direct access.\n- **Smart Reconnect**: Optional auto-reconnect and message buffering.\n- **Easy Setup**: Optional builder class for quick initialization.\n- **Well-Tested**: High test coverage, well-documented for extensibility.\n- **Module Support**: Supports CommonJS and ES6 modules.\n\n## Installation\n\nInstall `websocket-ts` with npm:\n\n```bash\n$ npm install websocket-ts \n```\n\n## Quickstart\nThis example shows how to use the package, complete with message buffering and automatic reconnection.\nThe created websocket will echo back any received messages. It will buffer messages when disconnected\nand attempt to reconnect every 1 second.\n\n```typescript\nimport {\n  ArrayQueue,\n  ConstantBackoff,\n  Websocket,\n  WebsocketBuilder,\n  WebsocketEvent,\n} from \"websocket-ts\";\n\n// Initialize WebSocket with buffering and 1s reconnection delay\nconst ws = new WebsocketBuilder(\"ws://localhost:8080\")\n  .withBuffer(new ArrayQueue())           // buffer messages when disconnected\n  .withBackoff(new ConstantBackoff(1000)) // retry every 1s\n  .build();\n\n// Function to output \u0026 echo received messages\nconst echoOnMessage = (i: Websocket, ev: MessageEvent) =\u003e {\n  console.log(`received message: ${ev.data}`);\n  i.send(`echo: ${ev.data}`);\n};\n\n// Add event listeners\nws.addEventListener(WebsocketEvent.open, () =\u003e console.log(\"opened!\"));\nws.addEventListener(WebsocketEvent.close, () =\u003e console.log(\"closed!\"));\nws.addEventListener(WebsocketEvent.message, echoOnMessage);\n```\n\n## Usage\nThis will demonstrate how to use `websocket-ts` in your project using the provided `WebsocketBuild`-class.\n\nFor a more detailed description of the API, please refer to the [API Documentation](https://jjxxs.github.io/websocket-ts/).\n\n#### Initialization\n\nCreate a new instance with the `WebsocketBuilder`:\n\n```typescript\nconst ws = new WebsocketBuilder(\"ws://localhost:42421\").build();\n```\n\n#### Events\n\nThere are six events which can be subscribed to through with event listeners:\n\n```typescript\nexport enum WebsocketEvent {\n  open = \"open\",          // Connection opened\n  close = \"close\",        // Connection closed\n  error = \"error\",        // Error-induced closure\n  message = \"message\",    // Message received\n  retry = \"retry\",        // Reconnect attempt\n  reconnect = \"reconnect\" // Successful reconnect\n}\n```\n\n#### Add Event Listeners\nEvent listeners receive the websocket instance (`i`) and the triggering event (`ev`) as arguments.\n\n ```typescript\n const ws = new WebsocketBuilder(\"ws://localhost:42421\")\n   .onOpen((i, ev) =\u003e console.log(\"opened\"))\n   .onClose((i, ev) =\u003e console.log(\"closed\"))\n   .onError((i, ev) =\u003e console.log(\"error\"))\n   .onMessage((i, ev) =\u003e console.log(\"message\"))\n   .onRetry((i, ev) =\u003e console.log(\"retry\"))\n   .onReconnect((i, ev) =\u003e console.log(\"reconnect\"))\n   .build();\n ```\n\n#### Remove Event Listeners\n\nTo unregister a specific event listener, use `removeEventListener`:\n\n```typescript\nlet ws: Websocket\n/* ... */\nws.removeEventListener(WebsocketEvent.open, openEventListener);\n```\n\n#### Send Message\n\nUse the `send` method to send a message to the server:\n\n```typescript\nlet ws: Websocket;\n/* ... */\nws.send(\"Hello World!\");\n```\n\n#### Reconnect \u0026 Backoff (Optional)\n\nIf you'd like the websocket to automatically reconnect upon disconnection, you can optionally provide a `Backoff` strategy. \nThis sets the delay between reconnection attempts. There are three built-in `Backoff` implementations, or you can create \nyour own by implementing the `Backoff` interface. If no Backoff is provided, the websocket will not attempt to reconnect.\n\n##### ConstantBackoff\n\nThe `ConstantBackoff` strategy enforces a fixed delay between each reconnection attempt. \nTo set a constant 1-second wait time, use:\n\n```typescript\nconst ws = new WebsocketBuilder(\"ws://localhost:42421\")\n  .withBackoff(new ConstantBackoff(1000)) // 1000ms = 1s\n  .build();\n```\n\n##### LinearBackoff\n\nThe `LinearBackoff` strategy increases the delay between reconnection attempts linearly,\nup to an optional maximum. For example, to start with a 0-second delay and increase by\n10 second for each retry, capping at 60 seconds, use:\n\n```typescript\nconst ws = new WebsocketBuilder(\"ws://localhost:42421\")\n  .withBackoff(new LinearBackoff(0, 10000, 60000)) // 0ms, 10s, 20s, 30s, 40s, 50s, 60s\n  .build();\n```\n\n##### ExponentialBackoff\n\nThe `ExponentialBackoff` strategy doubles the delay between each reconnection attempt, up\nto a specified maximum. This approach is inspired by the binary exponential backoff algorithm\ncommonly used in networking. For example, to generate a backoff series like `[1s, 2s, 4s, 8s]`, use:\n\n```typescript\nconst ws = new WebsocketBuilder(\"ws://localhost:42421\")\n  .withBackoff(new ExponentialBackoff(1000, 6)) // 1s, 2s, 4s, 8s, 16s, 32s, 64s\n  .build();\n```\n\n#### Buffer (Optional)\n\nTo buffer outgoing messages when the websocket is disconnected, you can optionally specify\na `Queue`. This queue will temporarily store your messages and send them in sequence when\nthe websocket (re)connects. Two built-in `Queue` implementations are available, or you can\ncreate your own by implementing the `Queue` interface. If no queue is provided, messages \nwon't be buffered.\n\n##### RingQueue\n\nThe `RingQueue` is a fixed-capacity, first-in-first-out (FIFO) queue. When it reaches capacity, \nthe oldest element is removed to accommodate new ones. Reading from the queue returns and\nremoves the oldest element. For instance, to set up a `RingQueue` with a 100-element capacity,\nuse:\n\n```typescript\nconst ws = new WebsocketBuilder(\"ws://localhost:42421\")\n  .withBuffer(new RingQueue(100))\n  .build();\n```\n\n##### ArrayQueue\n\nThe ArrayQueue offers an unbounded capacity, functioning as a first-in-first-out (FIFO) queue. \nReading from this queue returns and removes the oldest element. To use an `ArrayQueue`, use:\n\n```typescript\nconst ws = new WebsocketBuilder(\"ws://localhost:42421\")\n  .withBuffer(new ArrayQueue())\n  .build();\n```\n\n## Build \u0026 Tests\n\nTo compile the project, execute `npm run build`. \n\nTo run tests, use `npm run test`.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjjxxs%2Fwebsocket-ts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjjxxs%2Fwebsocket-ts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjjxxs%2Fwebsocket-ts/lists"}