• Stars
    star
    121
  • Rank 293,924 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

simple real-time messaging using WebRTC Data Channels and WebSockets

SocketPeer

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).

Features

  • 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)

Usage

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 to window a function called SocketPeer.

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.

Development

Installation

  1. If you haven't already, install Node.js (which includes npm).

  2. Clone this repository (cvan/socketpeer):

    git clone [email protected]:cvan/socketpeer.git
  3. In the root directory of the cloned repository of the project, install the Node dependencies:

    cd cvan/socketpeer/
    npm install
  4. 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.

Commands (npm scripts) for local development

  • npm run build (or npm run dist) โ€“ builds the distribution-ready files for SocketPeer (i.e., socketpeer.js, socketpeer.min.js), to the root project directory.
  • npm start (or npm 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 to npm as the socketpeer package.

Distribution

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 of SocketPeer (UMD-compatible).
  • socketpeer.min.js โ€“ the production-ready, minified version of SocketPeer (UMD-compatible).

Tests

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

Client API

peer = new SocketPeer([opts])

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 peers
  • socketFallback - when true, falls back to WebSockets when WebRTC is unavailable
  • socket - custom instance of a WebSocket connection to reuse
  • url - URL to WebSocket server
  • reconnect - when true, reconnects if peer connection drops
  • reconnectDelay - if reconnect is set, how long to wait (in milliseconds) before reconnecting
  • timeout - how long to wait (in milliseconds) before abandoning connection
  • autoconnect - when true, automatically connects upon page load
  • serveLibrary - when true, serves library at /socketpeer/socketpeer.js
  • debug - when true, logs debugging information to the console

peer.connect()

If reconnect or autoconnect is false, manually start the connection.

peer.send(data)

Send data to the remote peer.

peer.on(event, listener)

Adds a listener to the end of the listeners array for the specified event.

peer.off(event)

Remove listeners for the specified event.

SocketPeer extends Node's EventEmitter. See the docs for the remaining methods.

peer.close()

Destroy and cleanup this peer connection.

Events

peer.on('connect', function () {})

Fired when the peer connection and/or data channel is established.

peer.on('connect_error', function (data) {})

Fired when a connection error occurs.

peer.on('connect_timeout', function (data) {})

Fired when a connection timeout occurs.

peer.on('data', function (data) {})

Received a message from the remote peer.

peer.on('reconnect', function (data) {})

Fired when a reconnection occurs.

peer.on('reconnect_error', function (data) {})

Fired when a reconnection error occurs.

peer.on('reconnect_timeout', function (data) {})

Fired when a reconnection timeout occurs.

peer.on('upgrade', function (data) {})

Fired when a connection is successfully upgraded from WebSocket to RTCDataChannel.

peer.on('upgrade_attempt', function (data) {})

Fired when an upgrade attempt occurs.

peer.on('upgrade_error', function (data) {})

Fired when an upgrade error occurs.

peer.on('downgrade', function (data) {})

Fired when a connection falls back to WebSockets.

peer.on('close', function () {})

Called when the peer connection has closed.

peer.on('busy', function (err) {})

Fired when two clients are already connected using a same pair code. err is an Error object.

peer.on('error', function (err) {})

Fired when an error occurs. err is an Error object.

Server API

peerServer = new SocketPeerServer([opts])

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 the pairCode passed from the client (optional)

peerServer.socket

A property that links to the instance of ws.Server.

peerServer.server

A property that links to the instance of http.Server.

peerServer.leave(pairCode)

Breaks both ends of a peer connection (WebSocket or WebRTC).

Contributing

Contributions are very welcome!

Acknowledgments

Thank you to the following projects and individuals:

Licence

MIT Licence.

More Repositories

1

webvr360

It's like Tim Berners-Lee meets Oculus meets YouTube.
JavaScript
59
star
2

keyboardevent-key-polyfill

polyfill for `KeyboardEvent.prototype.key`
JavaScript
47
star
3

phantomHAR

a PhantomJS/SlimerJS script to generate HTTP Archive (HAR) data from captured network traffic
JavaScript
36
star
4

flexboxin5

flexbox in 5 minutes (mirror)
CSS
32
star
5

ghpages

a CLI tool to easily deploy your current working branch to GitHub Pages
JavaScript
20
star
6

tanx-1

tanx multiplayer webgl game
JavaScript
17
star
7

fastHAR-api

an API server that returns aggregated data from HTTP Archive (HAR) data from captured network traffic
JavaScript
9
star
8

tanx-client

JavaScript
7
star
9

navigator.onLine-that-actually-works

it really does
JavaScript
6
star
10

contains-pii

Search text for sensitive personal data
JavaScript
6
star
11

tagz

automatically tag tags and push aforementioned tags to GitHubโ„ข
Python
6
star
12

fastHAR

a front-end UI for aggregated HAR (HTTP Archive) data captured from network traffic
JavaScript
6
star
13

lunr-unicode-normalizer

an extension to lunr.js to normalize unicode characters by removing all diacritical marks
JavaScript
5
star
14

dom2screenshot

client-side tool for taking a screenshot of a DOM element and getting back a CORS'd CDN URL
JavaScript
5
star
15

flexbox-sort

sort a list of search results using flexbox (look mum, no DOM)
HTML
4
star
16

fetch-manifest

A nifty tool for fetching W3C Web-App Manifests
JavaScript
4
star
17

three-vrcontrols

three.js VR controls
JavaScript
3
star
18

cancorder

A browser extension to capture a video of a canvas.
JavaScript
3
star
19

aframe-role

Popmotion Role for A-Frame animation, tracking and physics.
JavaScript
3
star
20

moz-tanx

tanx game with mobile gamepad support (with server and client on same origin)
JavaScript
3
star
21

aframe-firebase-component

Firebase component for multiuser A-Frame.
JavaScript
3
star
22

cbir-portal

Web backend for Content-Based Image Retrieval (CBIR) suite
Python
3
star
23

secinv

Suite of tools to build a security inventory database
JavaScript
2
star
24

n64vr

Nintendo 64ยฎ in Virtual Reality
JavaScript
2
star
25

firesnaggle

a REST-ful API for generating a screenshot from a URL in Firefox (using slimerjs)
JavaScript
2
star
26

django-potato-captcha

A very simple, clever Django captcha application
Python
2
star
27

galaxy-designs

designs for mozilla galaxy v1
2
star
28

mirrormirror

Send `console.log` logs to a simple server.
JavaScript
2
star
29

DT2

Dead Trigger 2
JavaScript
2
star
30

github-live-comments

Live code comments on GitHub without refreshing the page
JavaScript
2
star
31

taro

a local browser using manifests as the data source
JavaScript
2
star
32

websdk

The Universal SDK for Web Applications.
JavaScript
2
star
33

secinv-client

Python
1
star
34

d

debug panel
HTML
1
star
35

marketplace-perfboard

JavaScript
1
star
36

focalStorage

a Promise-based, localStorage-like wrapper around IndexedDB
JavaScript
1
star
37

sfcal

event dates and times, names of movies, iMDB links
JavaScript
1
star
38

iconsnaggle

extract favicons, `link[rel="shortcut icon"]`, `link[rel="icon"]`, `link[rel="apple-touch-icon"]`, and `link[rel="og:image"]` icons from a given URL
JavaScript
1
star
39

irssi-annoyatron

an irssi IRC pager featuring growl *and* SMS notifications
Shell
1
star
40

seasearch

what-you-sea-is-what-you-get search
JavaScript
1
star
41

prana

Monitor your vital services with automated heartbeat checks.
Python
1
star
42

FLANN

FLANN - Fast Library for Approximate Nearest Neighbors
C
1
star
43

gamepad2keyboard

synthesises browser keyboard events from gamepad controls
JavaScript
1
star
44

country-flag-icons

pretty country flags
1
star
45

slacknow

Easy Slack auto-inviter service (using slackin) for multiple teams.
JavaScript
1
star
46

unity-webvr-arctic

Made with Mozilla's Unity WebVR Assets (https://github.com/mozilla/unity-webvr-export)
C#
1
star
47

dotfiles

Vim Script
1
star