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
|
Fires:
- PeerSoxClient#event:connectionEstablished
- PeerSoxClient#event:connectionClosed
- PeerSoxClient#event:peerConnected
- PeerSoxClient#event:peerTimeout
- PeerSoxClient#event:peerRtcClosed
Examples
// 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)
// 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
(static) EVENT_CONNECTION_ESTABLISHED :string
(static) EVENT_PEER_CONNECTED :string
(static) EVENT_PEER_TIMEOUT :string
(static) EVENT_PEER_WEBRTC_CLOSED :string
The peer connection via WebRTC has closed.
The connection might still be available via WebSocket.
(static) EVENT_SERVER_READY :string
(static) SUPPORTS :object
An object containing
Properties:
Name | Type | Description |
---|---|---|
SUPPORTS.WEBSOCKET |
boolean | |
SUPPORTS.WEBRTC |
boolean |
onBinary
Set the handler function for incoming binary data.
onString
Set the handler function for incoming string data.
status
Get the current status of the client.
Methods
close()
Close all connections and attempt to disconnect the peer.
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 |
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.
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.
destroy()
Delete the PeerSox instance.
Closes all open connections and removes event listeners.
getDeviceSupport() → {object}
Get information about the browser support of WebSocket and WebRTC.
getSocket() → {WebSocket}
Return the connected WebSocket socket.
Throws:
Will throw an error if no WebSocket connection is made.
init() → {Promise.<object>}
Initialize peersox by getting the config.
isConnected() → {boolean}
Return the current connection state.
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. |
Example
peersox.joinPairing('123456').then(pairing => {
if (pairing) {
// You can now connect to the server.
}
})
restorePairing() → {Promise.<(Pairing|null)>}
Restore a pairing.
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. |
Examples
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)
peersox.send('This is my message.')
// 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. |
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. |
validate(pairing) → {Promise.<boolean>}
Validate a pairing.
Parameters:
Name | Type | Description |
---|---|---|
pairing |
pairing |
The pairing to validate. |
Example
peersox.validate({ code: 123456, hash: 'xyz' }).then(isValid => {
// The pairing is valid.
})
Events
connectionClosed
The connection to the server has been closed.
connectionEstablished :Pairing
A connection to the server has been established.
peerConnected :Pairing
The peer is connected to this client.
peerRtcClosed :Pairing
The WebRTC connection to the peer closed.
peerTimeout :number
The peer connection has timed out.
serverReady
Config was requested from the server and a connection can be established.