PeerRTC is a simple javascript web module for easy peer to peer connection. PeerRTC is built on top of modern browser's WebRTC technology and also already handled most of the complicated parts in working with RTC technology. PeerRTC is packed with easy to call api for sending raw text, sending raw files, audio streaming, video streaming, connecting to peers via unique id and more.
- Add credits and attribution to this website when using the module.
- This module is still in beta phase and can be unstable.
- Source code contributions and bug reports are encouraged.
Using the sample sites below can be unstable since it uses github. It is adviseable to download the source code
and run it on your own machine.
Random Chat Site
Video Call and File Sharing Site
-
If you will be using the default PeerRTC backend server provided by us for testing purposes, you can skip this step. For own managed backend server, refer to PeerRTC server's repository. Server owned by us is unstable and not managed so it is recommended to host your own.
-
Add PeerRTC module in your html project's body.
<script type="text/javascript" src="https://PeerRTC.github.io/PeerRTC/peer.js"></script>
- Initialize the PeerRTC class in your main or index javascript file.
peer = new PeerRTC()
- Connect to the backend server.
onConnect = p=>{
// Code after successful connection to the server goes here
myId = p.id
console.log("Successfully connected to the server")
console.log("My Id: " + myId)
}
// true will only work if your server's url is SSL supported.
isSecure = true
// connect to the server
peer.start(isSecure, onConnect)
peer = new PeerRTC(serverURL, configurations)
serverURL
: optional
string
- The url in which the backend server is hosted. Not providing any url will use the default server url
PeerRTC.DEFAULT_SERVER_URL
. It is recommended to use your own rather than the default server since it is not stable.
configurations
: optional
json
- Json data that will be passed to the RTCPeerConnection
constructor. Not providing any will result in using the configurations with iceServers included provided by the default url
PeerRTC.DEFAULT_ICE_SERVER_SOURCE_URL
. The default url fetch the ice servers from our own hosted server.
peer.id
- Returns a unique id assigned by the server to this client.
peer.currentPeerId
- Returns the peer id this client is connected with. To connect with other peer, call the
connect
method.
peer.serverURL
- Returns the server url.
peer.configuration
- Returns the configurations set for RTCPeerConnection constructor.
peer.isConnectedToServer
- Returns whether connected to server that runs on the provided server url.
peer.mediaStream
- Returns the current media stream added by
addMediaStream
method.
peer.onpeerconnectsuccess = peerId=>{ }
- Called on successful connection to a peer via
connect
method.
peerId
: string
- The peer id of the peer successfully connected to.
peer.onpeerids = ids=>{}
- Called when
getAllPeerIds
method call is successful.
ids
: array
- Returns array of all peer ids connected to the server. Peer ids will only be returned if client ids are set
to be publicly available in the server.
peer.ontextmessage = text=>{ }
- Called when a new string message is received by the client. This is triggered when the peer client on the other end call the
sendText
method.
text
: string
- Returns the string message.
peer.onfilemessage = (fname, fileTotalSize, fileBytesArray, done)=>{}
- Called when a new file is received by the client.
fname
: string
- The filename of the current file received.
fileTotalSize
: number
- Total size of the file when completed in bytes.
fileBytesArray
: ArrayBuffer
- The array of bytes of the currently received parts of a file.
done
: boolean
- Whether the file is finished downloading or not.
peer.onsendfilemessage = (file, fileSizeSent)=>{}
- Triggered while currently uploading file to the connected peer.
file
: File
- The current file sending.
fileSizeSent
: number
- Current size of the part of the file being sent in bytes.
peer.oncloseP2P = ()=>{}
- Triggered when connection to a peer is closed.
peer.onclose = ()=>{}
- Triggered when connection to the server is closed.
peer.onnewpayload = payload=>{}
- Triggered when a new payload for the current client is added in the server. To add new payload, call the
addPayload
method.
payload
: json
- Returns the latest version of payload for this client stored in the server.
peer.onnewprivatepayload = payload =>{}
- Triggered when a new private payload for the current client is added in the server. To add new private payload, call the
addPrivatePayload
method.
payload
: json
- Returns the latest version of the private payload for this client stored in the server.
peer.onpeerpayloads = payloads=> {}
- Triggered as a result of calling
getAllPeerPayloads
method.
payloads
: array
- Array of payloads of all clients connected to the server. Client payloads will only be returned if client ids are set
to be publicly available in the config.json in the server in the server.
peer.onpeerconnectrequest = (peerId, accept, decline)=>{}
- Triggered when there is an incoming connection request from another peer.
peerId
: string
- The id of the peer attempting to connect.
accept
: function
- Calling this function wil establish connection to the requesting peer.
decline
: function
- Calling this function wil decline the connection request of the requesting peer.
peer.onpeerconnectdecline = peerId => {}
- Triggered when connection request to a peer has been denied.
peerId
: string
- The peerId that declines the connection request.
peer.onnewtrack = (newTrack, trackStreams) => {}
- Triggered when
addMediaStream
method was called by the connected peer.
newTrack
: MediaStreamTrack
- The newly added track object.
trackStreams
: MediaStreams
- The current stream object the
newTrack
parameter belongs to.
peer.onadminbroadcastdata = data =>{}
- Triggered by calling the
adminBroadcastData
method.
data
: object
- The data broadcasted by the admin.
peer.onadmingetallclientsdata = clientsData =>{}
- Triggered by calling
adminGetAllClientsData
method.
clientsData
: array
- Array of all clients data stored in the server.
peer.onadminactiondecline = ()=> {}
- Triggered when admin related actions are declined by the server due to any reasons.
peer.onservererror = event=>{}
- Triggered when server related error occurs.
event
: Event
- A parameter that is an Event instance that contains the errors.
peer.start(isSecure, onConnect)
- Call this method to initiate connection to the backend server .
isSecure
: boolean
- Setting this to true will use secure connection from client to the server. Setting the parameter to true is only applicable in
SSL supported
serverURLs
.
onConnect
: function
onConnect = (peer)=>{}
- A callback function after a successful connection to the server. The callback returns PeerRTC instance.
peer.pingServer(everyMillis, onserverping)
- Method to ping server within interval continously. Calling this method will remove any existing intervals that are doing the pings to the server. Use this
method to prevent idling problems in server.
everyMillis
: number
- Interval between each pings in milliseconds.
onserverping
: function
- Function that is called upon successful pings.
peer.clearServerPinger()
- Clears the existing interval that ping the server.
peer.connect(peerId)
- Used for connecting with other peer ids. The
onpeerconnectdecline
listener will be called if trying to connect on own id.
peerId
: string
- Peer id wanted to connect with.
peer.sendText(text)
- For sending string data. This method triggers the
ontextmessage
listener of the connected peer.
text
: string
- String message to send.
peer.sendFile(fname, file, chunkSize)
- For sending file. This method triggers the
onfilemessage
listener of the connected peer.
fname
: string
- Desired name for the file,
file
: File
- The file to be sent.
chunkSize
: number
, default=1024
- Size in bytes on how big is the chunk of the file that will be sent to the other end.
peer.addPayload(jsonData)
- For adding extra data or payload stored on the server associated to the current client. This data are also public and can be accessible to other peers when client ids are public available in config.json in the server in the server.
jsonData
: json
- Desired data payload to be store in the server associated to the current client.
peer.addPrivatePayload(jsonData)
- For adding private extra data or payload stored on the server associated to the current client.
jsonData
: json
- Desired private data payload to be store in the server associated to the current client.
peer.getAllPeerPayloads()
- For getting all peer payloads. Calling the method successfully will trigger
onpeerpayloads
listener. This method will not work properly if client public ids are not available to anyone in the config.json in the server in the server.
peer.getPeerPayload(peerId)
- Getting public payload of a specific peer.
peerId
: string
- Target peer id.
peer.closeP2P()
- For closing connection with another peer.
peer.close()
- For closing connection with the server.
peer.getAllPeerIds()
- For fetching all the peer ids from the server. Calling this method will trigger the
onpeerids
listener. This method will not work properly if client public ids are not available to anyone in the config.json in the server in the server.
peer.setMediaStream(stream)
- This method is used for sending MediaStream to another connected peer. This method can be used for video and audio call functionality. This method
also throws an error if the provided MediaStream contains more than one audio and video track.
Calling this method after successful call to
connect
method will only replace the earlier video and audio track. This means that providing a stream with video track in which it don't had any before calling theconnect
method will not work. The method can be use for switching rear and front camera functionality.
stream
: MediaStream
- This parameter is a MediaStream parameter that will be sent to another connected peer. The
onnewtrack
listener on another peer will be triggered by calling this method.
peer.updateBlob(fname, arrayBuffer)
- This method can be used in building Blob instance out of array buffer of a chunk of a file.
This method can be helpful when building a chunked file received from
onfilemessage
listener. Memory errors may occur when using this method especially when dealing large files.
fname
: string
File name parameter. File name should be unique because it is used as the primary key to identify the stored blobs in a map.
arrayBuffer
: ArrayBuffer
The chunked array buffer of a file parameter. Usually arrayBuffer
can be received from onfilemessage
listener.
peer.getBlob(fname)
- Getting a Blob instance stored in the PeerRTC instance.
fname
: string
- The unique file name of the blob being fetched.
peer.deleteBlob(fname)
- Deleting a Blob instance stored in the PeerRTC instance.
fname
: string
- The unique file name of the blob to be deleted.
peer.getAllBlobFiles()
- Returns an array of all stored Blob instance stored in the PeerRTC instance.
peer.deleteAllBlobFiles()
- Delete all the Blob instance stored in the PeerRTC instance.
peer.adminBroadcastData(key, data)
- A purposely private api to broadcast data to all clients. Calling this method will trigger
onadminbroadcastdata
of all clients.
key
: string
- A string that match tha sha56 hash in config.json in the server. Wrong key will trigger the
onadminactiondecline
method.
data
: object
- The data to be sent on all connected clients.
peer.adminGetAllClientsData(key)
- Method for getting all the clients data stored in the server including the private payloads. Successful call to this method
will trigger
onadmingetallclientsdata
listener
key
: string
- A string that match tha sha56 hash in config.json in the server. Wrong key will trigger the
onadminactiondecline
method.