{"id":17597854,"url":"https://github.com/cvan/socketpeer","last_synced_at":"2025-04-13T12:26:16.645Z","repository":{"id":28469903,"uuid":"31985780","full_name":"cvan/socketpeer","owner":"cvan","description":"simple real-time messaging using WebRTC Data Channels and WebSockets","archived":false,"fork":false,"pushed_at":"2017-09-29T03:44:15.000Z","size":142,"stargazers_count":120,"open_issues_count":22,"forks_count":22,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-10T16:29:40.962Z","etag":null,"topics":["javascript","multiplayer","realtime","webrtc","websockets"],"latest_commit_sha":null,"homepage":"https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/","language":"JavaScript","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/cvan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-03-10T22:42:04.000Z","updated_at":"2024-11-30T08:34:54.000Z","dependencies_parsed_at":"2022-09-04T04:40:30.263Z","dependency_job_id":null,"html_url":"https://github.com/cvan/socketpeer","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvan%2Fsocketpeer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvan%2Fsocketpeer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvan%2Fsocketpeer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvan%2Fsocketpeer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cvan","download_url":"https://codeload.github.com/cvan/socketpeer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248670437,"owners_count":21142904,"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":["javascript","multiplayer","realtime","webrtc","websockets"],"created_at":"2024-10-22T09:43:51.564Z","updated_at":"2025-04-13T12:26:16.601Z","avatar_url":"https://github.com/cvan.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# SocketPeer\n\nSimple 1:1 messaging via [WebRTC Data Channels](https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel) and [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n\n[Read this great **walk-through article**.](https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/)\n\n[**View a live demo** of a project using SocketPeer!](https://socketpeer-test.herokuapp.com/) See the (project's [source code](https://github.com/potch/test-socketpeer)).\n\n\n## Features\n\n* concise, [Node.js](https://nodejs.org/)-style API for **[WebRTC](https://en.wikipedia.org/wiki/WebRTC)** peer-to-peer connections\n* simple 1:1 peer connection signalling, pairing, and messaging\n* fallback WebSocket support if WebRTC Data Channels are unsupported\n* automatic reconnection if peer connections prematurely close\n* exports as a [UMD](https://github.com/umdjs/umd) module, so the library works everywhere (i.e., using [Browserify](http://browserify.org/), [webpack](https://webpack.js.org/), or included by a `\u003cscript\u003e` tag in any modern browser)\n\n\n## Usage\n\nIf you are requiring `socketpeer` as a Node package using [`npm`](https://www.npmjs.com)/[`yarn`](https://yarnpkg.com/) + [Browserify](http://browserify.org/)/[webpack](https://webpack.js.org/), install the [`socketpeer` package](https://www.npmjs.com/package/socketpeer) from your project directory like so:\n\n```sh\nnpm install socketpeer --save\n```\n\n\u003e **NOTE:** If you are **not** using Browserify/webpack, then use the included standalone file, [`socketpeer.min.js`](socketpeer.min.js), which exports to `window` a function called `SocketPeer`.\n\n[Read this great **walk-through article**.](https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/)\n\n[**View a live demo** of a project using SocketPeer!](https://socketpeer-test.herokuapp.com/) See the (project's [source code](https://github.com/potch/test-socketpeer)).\n\nAdditionally, here's some sample code to quickly get you started using `socketpeer`:\n\n```js\nvar socketpeer = require('socketpeer');\n\nvar peer = new SocketPeer({\n  pairCode: 'yolo',\n  url: 'http://localhost:3000/socketpeer/'\n});\n\npeer.on('connect', function () {\n  console.log('peer connected');\n});\n\npeer.on('connect_timeout', function () {\n  console.error('connection timed out (after %s ms)', peer.timeout);\n});\n\npeer.on('data', function (data) {\n  console.log('data received:', data);\n});\n\npeer.on('rtc.signal', function () {\n  console.log('WebRTC signalling');\n});\n\npeer.on('peer.found', function (data) {\n  console.log('peer found:', data.initiator);\n  peer.send('hello');\n});\n\npeer.on('upgrade', function () {\n  console.log('successfully upgraded WebSocket ⇒ to WebRTC peer connection');\n  peer.send('upgraded');\n});\n\npeer.on('upgrade_attempt', function () {\n  console.log('attempting to upgrade WebSocket ⇒ to WebRTC peer connection (attempt number: %d)', peer._connections.rtc.attempt);\n});\n\npeer.on('downgrade', function () {\n  console.log('downgraded WebRTC peer connection ⇒ to WebSocket connection');\n});\n\npeer.on('warning', function (data) {\n  console.error('warning:', data.message);\n});\n\npeer.on('error', function (err) {\n  console.error('error:', err);\n});\n```\n\nFor more examples, refer to the [`demo` directory](https://github.com/cvan/socketpeer/tree/master/demo).\n\n\n## Development\n\n### Installation\n\n1. If you haven't already, install [Node.js](https://nodejs.org/en/download/package-manager/) (which includes [`npm`](https://www.npmjs.com/)).\n2. Clone this repository ([`cvan/socketpeer`](https://github.com/cvan/socketpeer)):\n\n    ```sh\n    git clone git@github.com:cvan/socketpeer.git\n    ```\n3. In the root directory of the cloned repository of the project, install the [Node](https://nodejs.org/en/download/package-manager/) dependencies:\n\n    ```sh\n    cd cvan/socketpeer/\n    npm install\n    ```\n\n4. When all the latest dependencies are installed, from the `socketpeer/` directory, run these commands (each in a separate terminal tab):\n\n    ```sh\n    # Start the server for local development (includes server live-reloading).\n    npm start\n\n    # Run the Browserify watcher (files are written to the `build/` directory).\n    npm run watch\n    ```\n\n    This will generate a non-minified version of the library and will run a watcher which recompiles the `socketpeer` library when local changes are saved to disk.\n\n\n### Commands (`npm` scripts) for local development\n\n* **`npm run build`** (or `npm run dist`) – builds the distribution-ready files for `SocketPeer` (i.e., [`socketpeer.js`](socketpeer.js), [`socketpeer.min.js`](socketpeer.min.js)), to the root project directory.\n* **`npm start`** (or `npm run dev`) – builds the development version of the library and runs a file watcher.\n* **`npm run test`** – runs the tests.\n* **`npm run test-local`** – runs the tests in a continuous-watch mode (useful for local, test-driven development).\n* **`npm run release`** – deploy the current project directory as a module to `npm` as the [`socketpeer` package](https://www.npmjs.com/package/socketpeer).\n\n## Distribution\n\nTo build the Browserify bundles:\n\n```sh\nnpm run build\n```\n\nTwo files will be written to this project's root directory:\n\n* **[`socketpeer.js`](socketpeer.js)** – the development/debug-purposed, unminified version of `SocketPeer` (UMD-compatible).\n* **[`socketpeer.min.js`](socketpeer.min.js)** – the production-ready, minified version of `SocketPeer` (UMD-compatible).\n\n\n\n## Tests\n\nRefer to these docs for setting up continuous-integration testing locally:\n\n* [Sauce Labs](https://github.com/defunctzombie/zuul/wiki/cloud-testing)\n* [Travis CI](https://github.com/defunctzombie/zuul/wiki/Travis-ci)\n\nTo run the tests intended for a local environment:\n\n```sh\nnpm run test-local\n```\n\nTo run the tests in \"the cloud\" (e.g., [Sauce Labs](https://saucelabs.com/), [Travis CI](https://travis-ci.org/)):\n\n```sh\nnpm test\n```\n\n\n## Client API\n\n### `peer = new SocketPeer([opts])`\n\nCreate a new peer WebRTC Data Channel peer connection (only WebRTC if `socketFallback` is `false`).\n\nA \"data channel\" for text/binary communication is always established, because it's cheap and often useful.\n\nIf `opts` is specified, then the default options (shown below) will be overridden.\n\n```js\n{\n  pairCode: '\u003crandom string\u003e',\n  socketFallback: true,\n  socket: [Object],\n  url: 'http://localhost',\n  reconnect: true,\n  reconnectDelay: 1000,\n  timeout: 10000,\n  autoconnect: true,\n  serveLibrary: true,\n  debug: false\n}\n```\n\nThe options do the following:\n\n* `pairCode` - string used to identify peers\n* `socketFallback` - when `true`, falls back to WebSockets when WebRTC is unavailable\n* `socket` - custom instance of a WebSocket connection to reuse\n* `url` - URL to WebSocket server\n* `reconnect` - when `true`, reconnects if peer connection drops\n* `reconnectDelay` - if `reconnect` is set, how long to wait (in milliseconds) before reconnecting\n* `timeout` - how long to wait (in milliseconds) before abandoning connection\n* `autoconnect` - when `true`, automatically connects upon page load\n* `serveLibrary` - when `true`, serves library at `/socketpeer/socketpeer.js`\n* `debug` - when `true`, logs debugging information to the `console`\n\n### `peer.connect()`\n\nIf `reconnect` or `autoconnect` is `false`, manually start the connection.\n\n### `peer.send(data)`\n\nSend data to the remote peer.\n\n### `peer.on(event, listener)`\n\nAdds a listener to the end of the listeners array for the specified `event`.\n\n### `peer.off(event)`\n\nRemove listeners for the specified `event`.\n\nSocketPeer extends Node's [`EventEmitter`](https://nodejs.org/api/events.html). See the docs for the remaining methods.\n\n### `peer.close()`\n\nDestroy and cleanup this peer connection.\n\n\n## Events\n\n### `peer.on('connect', function () {})`\n\nFired when the peer connection and/or data channel is established.\n\n### `peer.on('connect_error', function (data) {})`\n\nFired when a connection error occurs.\n\n### `peer.on('connect_timeout', function (data) {})`\n\nFired when a connection timeout occurs.\n\n### `peer.on('data', function (data) {})`\n\nReceived a message from the remote peer.\n\n### `peer.on('reconnect', function (data) {})`\n\nFired when a reconnection occurs.\n\n### `peer.on('reconnect_error', function (data) {})`\n\nFired when a reconnection error occurs.\n\n### `peer.on('reconnect_timeout', function (data) {})`\n\nFired when a reconnection timeout occurs.\n\n### `peer.on('upgrade', function (data) {})`\n\nFired when a connection is successfully upgraded from WebSocket to RTCDataChannel.\n\n### `peer.on('upgrade_attempt', function (data) {})`\n\nFired when an upgrade attempt occurs.\n\n### `peer.on('upgrade_error', function (data) {})`\n\nFired when an upgrade error occurs.\n\n### `peer.on('downgrade', function (data) {})`\n\nFired when a connection falls back to WebSockets.\n\n### `peer.on('close', function () {})`\n\nCalled when the peer connection has closed.\n\n### `peer.on('busy', function (err) {})`\n\nFired when two clients are already connected using a same pair code. `err` is an `Error` object.\n\n### `peer.on('error', function (err) {})`\n\nFired when an error occurs. `err` is an `Error` object.\n\n\n## Server API\n\n### `peerServer = new SocketPeerServer([opts])`\n\nCreate a new server for establishing peer connections (i.e., \"signalling\") and passing WebSocket messages through (if WebRTC Data Channel not supported).\n\nIf `httpServer` is specified, that existing server will be used instead and a `ws.Server` will be created and attached to it. To use an existing `ws.Server` for signalling, pass `wsServer`.\n\nIf `opts` is specified, then the default options (shown below) will be overridden.\n\n```js\n{\n  allowedOrigins: [Array],\n  httpServer: undefined,\n  wsServer: undefined,\n  peerTimeout: 60000,\n  pairCodeValidator: function (pairCode) {}\n}\n```\n\nThe options do the following:\n\n* `allowedOrigins` - array of allowed/whitelisted origins (optional)\n* `peerTimeout` - how long to wait (in milliseconds) before abandoning peer connection (defaults to 6000 milliseconds / 1 minute)\n* `pairCodeValidator` - function that allows custom validation on the `pairCode` passed from the client (optional)\n\n### `peerServer.socket`\n\nA property that links to the instance of [**`ws.Server`**](https://github.com/websockets/ws).\n\n### `peerServer.server`\n\nA property that links to the instance of `http.Server`.\n\n### `peerServer.leave(pairCode)`\n\nBreaks both ends of a peer connection (WebSocket or WebRTC).\n\n\n## Contributing\n\n[Contributions are very welcome!](CONTRIBUTING.md)\n\n\n## Acknowledgments\n\nThank you to the following projects and individuals:\n\n* [`simple-peer`](https://github.com/feross/simple-peer) (Licensed under [MIT](https://github.com/feross/simple-peer/blob/master/LICENSE))\n\n\n## Licence\n\n[MIT Licence.](LICENCE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcvan%2Fsocketpeer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcvan%2Fsocketpeer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcvan%2Fsocketpeer/lists"}