Simple 1:1 messaging via WebRTC Data Channels and WebSockets.
Read this great walk-through article.
View a live demo of a project using SocketPeer! See the (project's source code).
- concise, Node.js-style API for WebRTC peer-to-peer connections
- simple 1:1 peer connection signalling, pairing, and messaging
- fallback WebSocket support if WebRTC Data Channels are unsupported
- automatic reconnection if peer connections prematurely close
- exports as a UMD module, so the library works everywhere (i.e., using Browserify, webpack, or included by a
<script>
tag in any modern browser)
If you are requiring socketpeer
as a Node package using npm
/yarn
+ Browserify/webpack, install the socketpeer
package from your project directory like so:
npm install socketpeer --save
NOTE: If you are not using Browserify/webpack, then use the included standalone file,
socketpeer.min.js
, which exports towindow
a function calledSocketPeer
.
Read this great walk-through article.
View a live demo of a project using SocketPeer! See the (project's source code).
Additionally, here's some sample code to quickly get you started using socketpeer
:
var socketpeer = require('socketpeer');
var peer = new SocketPeer({
pairCode: 'yolo',
url: 'http://localhost:3000/socketpeer/'
});
peer.on('connect', function () {
console.log('peer connected');
});
peer.on('connect_timeout', function () {
console.error('connection timed out (after %s ms)', peer.timeout);
});
peer.on('data', function (data) {
console.log('data received:', data);
});
peer.on('rtc.signal', function () {
console.log('WebRTC signalling');
});
peer.on('peer.found', function (data) {
console.log('peer found:', data.initiator);
peer.send('hello');
});
peer.on('upgrade', function () {
console.log('successfully upgraded WebSocket ⇒ to WebRTC peer connection');
peer.send('upgraded');
});
peer.on('upgrade_attempt', function () {
console.log('attempting to upgrade WebSocket ⇒ to WebRTC peer connection (attempt number: %d)', peer._connections.rtc.attempt);
});
peer.on('downgrade', function () {
console.log('downgraded WebRTC peer connection ⇒ to WebSocket connection');
});
peer.on('warning', function (data) {
console.error('warning:', data.message);
});
peer.on('error', function (err) {
console.error('error:', err);
});
For more examples, refer to the demo
directory.
-
If you haven't already, install Node.js (which includes
npm
). -
Clone this repository (
cvan/socketpeer
):git clone [email protected]:cvan/socketpeer.git
-
In the root directory of the cloned repository of the project, install the Node dependencies:
cd cvan/socketpeer/ npm install
-
When all the latest dependencies are installed, from the
socketpeer/
directory, run these commands (each in a separate terminal tab):# Start the server for local development (includes server live-reloading). npm start # Run the Browserify watcher (files are written to the `build/` directory). npm run watch
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.
npm run build
(ornpm run dist
) – builds the distribution-ready files forSocketPeer
(i.e.,socketpeer.js
,socketpeer.min.js
), to the root project directory.npm start
(ornpm run dev
) – builds the development version of the library and runs a file watcher.npm run test
– runs the tests.npm run test-local
– runs the tests in a continuous-watch mode (useful for local, test-driven development).npm run release
– deploy the current project directory as a module tonpm
as thesocketpeer
package.
To build the Browserify bundles:
npm run build
Two files will be written to this project's root directory:
socketpeer.js
– the development/debug-purposed, unminified version ofSocketPeer
(UMD-compatible).socketpeer.min.js
– the production-ready, minified version ofSocketPeer
(UMD-compatible).
Refer to these docs for setting up continuous-integration testing locally:
To run the tests intended for a local environment:
npm run test-local
To run the tests in "the cloud" (e.g., Sauce Labs, Travis CI):
npm test
Create a new peer WebRTC Data Channel peer connection (only WebRTC if socketFallback
is false
).
A "data channel" for text/binary communication is always established, because it's cheap and often useful.
If opts
is specified, then the default options (shown below) will be overridden.
{
pairCode: '<random string>',
socketFallback: true,
socket: [Object],
url: 'http://localhost',
reconnect: true,
reconnectDelay: 1000,
timeout: 10000,
autoconnect: true,
serveLibrary: true,
debug: false
}
The options do the following:
pairCode
- string used to identify peerssocketFallback
- whentrue
, falls back to WebSockets when WebRTC is unavailablesocket
- custom instance of a WebSocket connection to reuseurl
- URL to WebSocket serverreconnect
- whentrue
, reconnects if peer connection dropsreconnectDelay
- ifreconnect
is set, how long to wait (in milliseconds) before reconnectingtimeout
- how long to wait (in milliseconds) before abandoning connectionautoconnect
- whentrue
, automatically connects upon page loadserveLibrary
- whentrue
, serves library at/socketpeer/socketpeer.js
debug
- whentrue
, logs debugging information to theconsole
If reconnect
or autoconnect
is false
, manually start the connection.
Send data to the remote peer.
Adds a listener to the end of the listeners array for the specified event
.
Remove listeners for the specified event
.
SocketPeer extends Node's EventEmitter
. See the docs for the remaining methods.
Destroy and cleanup this peer connection.
Fired when the peer connection and/or data channel is established.
Fired when a connection error occurs.
Fired when a connection timeout occurs.
Received a message from the remote peer.
Fired when a reconnection occurs.
Fired when a reconnection error occurs.
Fired when a reconnection timeout occurs.
Fired when a connection is successfully upgraded from WebSocket to RTCDataChannel.
Fired when an upgrade attempt occurs.
Fired when an upgrade error occurs.
Fired when a connection falls back to WebSockets.
Called when the peer connection has closed.
Fired when two clients are already connected using a same pair code. err
is an Error
object.
Fired when an error occurs. err
is an Error
object.
Create a new server for establishing peer connections (i.e., "signalling") and passing WebSocket messages through (if WebRTC Data Channel not supported).
If 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
.
If opts
is specified, then the default options (shown below) will be overridden.
{
allowedOrigins: [Array],
httpServer: undefined,
wsServer: undefined,
peerTimeout: 60000,
pairCodeValidator: function (pairCode) {}
}
The options do the following:
allowedOrigins
- array of allowed/whitelisted origins (optional)peerTimeout
- how long to wait (in milliseconds) before abandoning peer connection (defaults to 6000 milliseconds / 1 minute)pairCodeValidator
- function that allows custom validation on thepairCode
passed from the client (optional)
A property that links to the instance of ws.Server
.
A property that links to the instance of http.Server
.
Breaks both ends of a peer connection (WebSocket or WebRTC).
Contributions are very welcome!
Thank you to the following projects and individuals:
simple-peer
(Licensed under MIT)