A JavaScript Library for PieSocket Realtime.
Note: This package is PieSocket Client SDK (to be used with frontend on browsers), if you are looking for the NodeJS Server SDK, please see PieSocket-NodeJS.
See CHANGELOG.md for release notes.
Yarn
yarn add piesocket-js
NPM
npm i piesocket-js
CDN
<script src="https://unpkg.com/piesocket-js@7"></script>Import module:
import PieSocket from 'piesocket-js';With CDN/Browser:
Use the PieSocket.default global variable, e.g. var piesocket = new PieSocket.default({...})
PieSocketJS offers Channels, Portals (v3) and PieRTC (v4).
Channels are realtime PubSub connections over WebSocket, they allow you to:
- Subscribe to events on client side
- Publish events from server
- Publish events from client with C2C feature.
See the Channels documentation to learn more about how to use Channels.
Pass version: 4 to share a single WebSocket across every subscribe()
call. Each subscribe() still returns a Channel with the same
listen / publish / member API — the multiplexing is transparent:
const piesocket = new PieSocket({ version: 4, clusterId: 'xxxxx', apiKey: 'yyyyy' });
const chat = await piesocket.subscribe('chat-room'); // opens the socket
const alerts = await piesocket.subscribe('alerts'); // rides the same socket
chat.listen('message', (data) => { /* ... */ });
alerts.publish('ping', { at: Date.now() });Notes for v4:
- Presence is delta-based. The full roster arrives once; after that
Channel.membersis kept in sync from join/leave deltas. Callchannel.refreshMembers()to re-sync from the server on demand. - Binary needs no opt-in. Any binary frame is delivered as a
system::binaryevent (anArrayBuffer). Note the double colon — all v4 system events (system::member_joined,system::binary, etc.) use it, unlike v3's single-colonsystem:events. Binary sent on the primary channel goes straight over the wire as raw bytes; on a secondary channel it's base64-encoded first (there's no way to tag raw bytes with a channel, unlike JSON frames) — transparent tochannel.send()/channel.listen()either way, just with the usual ~33% base64 overhead on a secondary channel's message-size limit. - Unsubscribing the connect-time channel promotes another subscribed channel to keep the connection alive; a few in-flight frames may be missed during the swap.
- Video/audio rooms (
subscribe(channel, {video: true})etc.) ride the same shared connection as everything else underversion: 4— see PieRTC below.
Portals are programmable video streams over WebRTC (v3), they allow you to build powerful video applications.
See the Portals documentation to learn more about how to use Portals.
PieRTC is the v4 counterpart to Portals: the same programmable WebRTC video/audio rooms, but multiplexed onto v4's shared connection instead of a dedicated socket per room.
const piesocket = new PieSocket({ version: 4, notifySelf: true, clusterId: 'xxxxx', apiKey: 'yyyyy' });
const room = await piesocket.subscribe('video-room', {
video: true,
onLocalVideo: (stream) => { /* attach to a <video> element */ },
onParticipantJoined: (uuid, stream) => { /* attach remote stream */ },
onParticipantLeft: (uuid) => { /* remove remote stream */ },
});Notes:
- Pass
video: true,audio: true, orpieRTC: trueinsubscribe()'s second argument to mark a room as a PieRTC room — the channel is attached a.pieRTCinstance once subscribed. Note this ispieRTC, not v3 Portal'sportal— underversion: 4,portal: truealone will not attach PieRTC. - Signalling frames use their own
rtc::namespace (rtc::offer,rtc::answer,rtc::candidate, etc.) — separate from both v3'ssystem:and v4'ssystem::conventions, so they're never mistaken for control frames. - Set
notifySelf: trueon thePieSocketconstructor if this is the firstsubscribe()call (it opens the shared connection) — PieRTC relies on it the same way v3 Portals do. If a PieRTC room is subscribed onto a socket that's already open without it, a console warning is logged since it can't be changed after the fact. notifySelfis connection-wide under v4, not per-channel. If a PieRTC room'ssubscribe()call is the one that opens the shared socket, every other channel multiplexed onto that same socket also getsnotifySelfforced on — v4 has no per-channel override for it. If you need a plain channel withnotifySelfoff alongside a PieRTC room,subscribe()the plain channel first so it opens the primary connection.- Re-subscribing to an already-open channel does not retroactively attach
PieRTC.
subscribe('room', {video: true})only attaches.pieRTCthe first time a channel is subscribed — a latersubscribe('room', {video: true})call for the same channel ID just returns the existing (non-PieRTC) channel handle, with a console warning.unsubscribe()first if you need to turn a plain channel into a PieRTC room.
Complete list of allowed configuration options
| Option | Description | Default |
|---|---|---|
| apiKey | Required, Your PieSocket API key. | Demo key |
| version | Protocol version. Set to 4 for multi-channel multiplexing over one connection. |
3 |
| clusterId | Your API key's cluster ID. | demo |
| clusterDomain | For self hosted endpoints (localhost:4001) or custom domains in managed Piesocket | null |
| ssl | Set to false to use ws:// protocol, useful for self-hosted servers |
true |
| consoleLogs | Logs useful connection info if set to true. |
false |
| notifySelf | Receive messages sent by self, pass 0 to disabled. |
1 |
| jwt | JWT authentication token, skips authentication endpoint call. | null |
| presence | Enable presence events on any channel, pass 1 to enabled. |
0 |
| authEndpoint | Authentication endpoint for private channels. | /broadcasting/auth |
| authHeaders | Headers to include with authEndpoint call. | {} |
| forceAuth | Force authentication on all channels. | false |
| userId | User ID, used when user does not exists in JWT payload. |
anonymous |
| blockchainTestMode | Enable/disable test mode, defaults to false i.e., Ethereum main network. Set to true for Rinkeby test network. |
false |
| blockchainGasFee | Gas fee to set on Ethereum contract calls | 41000 |
List of available methods on the PieSocket object
| Method | Description | Returns |
|---|---|---|
| subscribe(channelId, roomOptions) | Subscribe to a channel. Pass {video: true}, {audio: true}, or {portal: true} (v3) / {pieRTC: true} (v4) in roomOptions for a WebRTC room. |
Channel Object |
| unsubscribe(channelId) | Un-subscribe from a channel. | Boolean |
| getConnections() | Get list of all active connections/channels for this client. | Object |
List of available methods on the Channel object
| Method | Description |
|---|---|
| listen("event-name", callback) | Listen to an event. |
| publish("event-name", data, meta) | Publish message from client. |
| getMemberByUUID(uuid) | Get a Presence member from their uuid. |
| refreshMembers() | (v4) Re-sync the presence roster from the server. Returns a Promise of the member list. |
| .portal / .pieRTC | Set on a WebRTC room channel — .portal under v3, .pieRTC under v4. See Portals / PieRTC. |
| on("lifecycle-event", callback) | Listen to lifecycle events on the native WebSocket connection. |
| confirmOnBlockchain(event, transaction_hash) | Create a proof-of-witness for a Blockchain message, on receiver's end. |
- Clone the repo
git clone git@github.com:piesocket/piesocket-js.git - Run
npm install - Run
npm start - Open
http://localhost:8080in browser
Now you can interactively test the SDK, add features and fix bugs.
Documentation: PieSocket Realtime Docs