PeerSoxClient

PeerSoxClient

The client pairs another client via the server.

A running PeerSox server is required for pairing – two clients can't pair with eachother without a server.

Usage is different between the initiator (the one to request a pairing code) and the joiner (the one to validate a pairing code).

Constructor

new PeerSoxClient(url, options)

Create a new PeerSox client.

Parameters:
Name Type Default Description
url string http://localhost:3000

The URL where the PeerSox server is reachable.

options object

The options for the client.

Properties
Name Type Description
autoUpgrade boolean

Automatically upgrade to a WebRTC connection.

debug boolean

When enabled, debugging info is logged.

simplePeerOptions object

Options passed to SimplePeer.

peerTimeout number

How long in seconds before closing peer connection.

Source:
Fires:
Examples

The initiator

// Create a new client.
let peersox = new PeerSoxClient('http://localhost:3000', {
  debug: true
})

await peersox.init()

// Once the joiner (the peer of this client) is connected, we can start
// listening for incoming messages.
peersox.on('peerConnected', () => {
  // Receive binary data (e.g. ArrayBuffer).
  peersox.onBinary = (data) => {
    const buffer = new Uint8Array(data);
    console.log(buffer)
  }

  // Receive string data.
  peersox.onString = (data) => {
    console.log(data)
  }
})

// Request a new Pairing.
// If successful, the client is now connected to the PeerSox server and
// waiting for the joiner to connet to the server.
const pairing = await peersox.createPairing()

// The pairing code the joiner will need to use.
console.log(pairing.code) // => "123456"

// Connect with the received pairing.
peersox.connect(pairing)

The joiner

// Create a new client.
let peersox = new PeerSoxClient('http://localhost:3000', {
  debug: true
})

await peersox.init()

// Start pairing with the initiator.
const pairing = await peersox.joinPairing('123456')

// The pairing with the peer succeeded when the following event is emitted.
peersox.on('peerConnected', () => {
  // The client is now connected to its peer.
  // Let's send a message every second.
  interval = window.setInterval(() => {
    const numbers = [
      Math.round(Math.random() * 100),
      Math.round(Math.random() * 100),
      Math.round(Math.random() * 100)
    ]

    const byteArray = new Uint8Array(numbers)

    // Send an ArrayBuffer.
    peersox.send(byteArray.buffer)

    // Send a string.
    peersox.send(numbers.join(';'))
  }, 1000)
})

// You can now connect with the pairing.
peersox.connect(pairing)

Extends

Members

(static) EVENT_CONNECTION_CLOSED :string

Source:

(static) EVENT_CONNECTION_ESTABLISHED :string

Source:

(static) EVENT_PEER_CONNECTED :string

Source:

(static) EVENT_PEER_TIMEOUT :string

Source:

(static) EVENT_PEER_WEBRTC_CLOSED :string

The peer connection via WebRTC has closed.

The connection might still be available via WebSocket.

Source:

(static) EVENT_SERVER_READY :string

Source:

(static) SUPPORTS :object

An object containing

Properties:
Name Type Description
SUPPORTS.WEBSOCKET boolean
SUPPORTS.WEBRTC boolean
Source:

onBinary

Set the handler function for incoming binary data.

Source:

onString

Set the handler function for incoming string data.

Source:

status

Get the current status of the client.

Source:

Methods

close()

Close all connections and attempt to disconnect the peer.

Source:

connect(pairing) → {Promise.<{pairing:Pairing, isInitiator:boolean}>}

Connect to the WebSocket server with the given pairing.

This will directly attempt a connection to the WebSocket server, without prior validation of the pairing. The client and server will first perform a handshake, where the pairing is validated. The connection will be closed immediately if the handshake fails, without emitting any of the events.

The server will decide the role (initiator or joiner) of this client depending on who was first.

The promise can be rejected when the WebSocket server is not available, when too many requests are made or when the WebSocket server refuses the handshake with the fetched pairing.

Parameters:
Name Type Description
pairing Pairing
Source:
Example
peersox.connect({ code: 123456, hash: 'xyz' }).then(({ pairing, isInitiator }) => {
  // You are now connected to the server.

  peersox.on('peerConnnected', () => {
    // You can now send messages to the other client.
  })
})

createPairing() → {Promise.<Pairing>}

Initiate a pairing.

The method will call the API to fetch a new Pairing, consisting of the code and hash. The pairing is valid for a limited amount of time, depending on the configuration done on the server side.

The promise can be rejected when the API is not available or when too many requests are made.

Source:
Example
peersox.createPairing().then(pairing => {
  // The pairing code the joiner will need to use.
  // => { hash: 'xyzxyzxyz', code: '123456' }
  console.log(pairing)
})

deletePairing()

Delete all pairing cookies.

Source:

destroy()

Delete the PeerSox instance.

Closes all open connections and removes event listeners.

Source:

getDeviceSupport() → {object}

Get information about the browser support of WebSocket and WebRTC.

Source:

getSocket() → {WebSocket}

Return the connected WebSocket socket.

Source:
Throws:

Will throw an error if no WebSocket connection is made.

init() → {Promise.<object>}

Initialize peersox by getting the config.

Source:

isConnected() → {boolean}

Return the current connection state.

Source:

joinPairing(code) → {Promise.<Pairing>}

Join an initiated pairing.

The given code is from a Pairing. It is first validated via the API and if this is successful, a WebSocket connection to the server is attempted.

Parameters:
Name Type Description
code number | string

The code to validate.

Source:
Example
peersox.joinPairing('123456').then(pairing => {
  if (pairing) {
    // You can now connect to the server.
  }
})

restorePairing() → {Promise.<(Pairing|null)>}

Restore a pairing.

Source:

send(data)

Send data to the peer.

It's possible to send either string or binary data. Performance is likely to be better when sending binary data, for example an ArrayBuffer.

This method will not perform any checks on the validity or compatibility of the given data's type with WebSocket or WebRTC.

Parameters:
Name Type Description
data string | ArrayBuffer

The data to send to the peer.

Source:
Examples

Sending binary data

const numbers = [
  Math.round(Math.random() * 100),
  Math.round(Math.random() * 100),
  Math.round(Math.random() * 100)
]
const byteArray = new Uint8Array(numbers)
peersox.send(byteArray.buffer)

Sending a string

peersox.send('This is my message.')

Sending an object

// It's not possible to send objects directly. You need to stringify it and
// send it as a string.
const payload = {
  name: 'ping',
  data: Date.now()
}
const message = JSON.stringify(payload)
peersox.send(message)

storePairing(pairing)

Save the given pairing in a cookie.

Parameters:
Name Type Description
pairing Pairing

The pairing to save.

Source:

upgrade(isInitiator)

Upgrade the connection to WebRTC.

Call this method when you disabled automatic upgrading.

Parameters:
Name Type Description
isInitiator boolean

Whether this client is initiating.

Source:

validate(pairing) → {Promise.<boolean>}

Validate a pairing.

Parameters:
Name Type Description
pairing pairing

The pairing to validate.

Source:
Example
peersox.validate({ code: 123456, hash: 'xyz' }).then(isValid => {
  // The pairing is valid.
})

Events

connectionClosed

The connection to the server has been closed.

Source:

connectionEstablished :Pairing

A connection to the server has been established.

Source:

peerConnected :Pairing

The peer is connected to this client.

Source:

peerRtcClosed :Pairing

The WebRTC connection to the peer closed.

Source:

peerTimeout :number

The peer connection has timed out.

Source:

serverReady

Config was requested from the server and a connection can be established.

Source: