README
PieSocket JavaScript Client
A JavaScript Library for PieSocket Channels.
PieSocket Channels are a medium for clients and servers to communicate in real-time. Client-to-client communications are also supported.
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.
Installation
Yarn
yarn add piesocket-js
NPM
npm i piesocket-js
CDN
<script src="https://unpkg.com/piesocket-js@1"></script>
Importing
Import module:
import PieSocket from 'piesocket-js';
With CDN/Browser:
Use the PieSocket global variable
Subscribe On Frontend
- Initialize PieSocket:
var piesocket = new PieSocket({
clusterId: 'YOUR_CLUSTER_ID',
apiKey: 'YOUR_API_KEY'
});
Reference: Complete list of configuration options
- Subscribe to a channel:
piesocket.subscribe(channelId);
Above method returns a Promise, which is resolved when the WebSocket connection is ready.
- Listen to an event:
piesocket.subscribe(channelId).then(channel => {
//Connection is now open
channel.listen('event-name', function(data, meta){
console.log("event-name received: ", data, meta);
});
})
or, Listen to all events:
channel.listen('*', function(event, data, meta){
console.log(`${event} received: `, data, meta);
});
- Listen to lifecycle events
channel.on('close', function(event){
console.log("PieSocket disconnected!");
});
Following life-cycle events are available:
message: Fired when WebSocket message is received.error: Fired when WebSocket connection errors occur.close: Fired when WebSocket connection is closed.blockchain-error: Fired when Blockchain errors occur.blockchain-hash: Fired when Blockchain contract's transaction hash is available.
Publish Events From Browser
You can publish messages directly from the client. Enable C2C (Client to client) communication for the API key from your PieSocket account to do the following.
channel.publish("event-name", data, meta);
Parameters:
data: JSON data for the event.meta: Optional information about the event in JSON format.
Publish Events From Server
Use the following POST request to publish a message from your server.
POST /api/publish HTTP/1.1
Host: CLUSTER_ID.piesocket.com
Content-Type: application/json
{
"key": "API_KEY",
"secret": "API_SECRET",
"channelId": "CHANNEL_ID",
"message": { "event": "new-tweet", "data": { "text": "Hello @PieSocketAPI!" }, "meta": { "user": 143 } }
}
See code examples for this request in PHP, NodeJS, Ruby, Python, Java, and Go in PieSocket documentation.
Blockchain Realtime
Send 100% trustworthy messages to connected peers and maintain a proof of the message on the Ethereum Blockchain network.
To send a message on the Blockhain
channel.publish("event-name", data, {
blockchain: true
});
payload should be a string.
User will have to sign this message using the MetaMask Ethereum Wallet.
Optinally, to confirm a message on the receiver's end, to create a proof-of-acceptance on the Blockchain. Use the following method.
channel.listen("event-name", function(data, meta){
if(meta && meta.blockchain && meta.transaction_hash){
//This is blockchain message, accept the contract on Ethereum blockchain.
channel.confirmOnBlockchain("blockchain-confirmation", meta.transaction_hash);
}
})
meta.transaction_hash is the transaction hash for the initial blockchain message.
Above code emits an event blockchain-confirmation with the confirmation contract's transaction hash in meta.
To get a list of blockchain messages pending acceptance, use the REST API.
PieSocket Methods
List of available methods on the PieSocket object
| Method | Description | Returns |
|---|---|---|
| subscribe(channelId) | Subscribe to a channel. | Channel Object |
| unsubscribe(channelId) | Un-subscribe from a channel. | Boolean |
| getConnections() | Get list of all active connections/channels for this client. | Object |
PieSocket Channel Methods
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. |
| 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. |
Configuration
Complete list of allowed configuration options
| Option | Description | Default |
|---|---|---|
| apiKey | Required, Your PieSocket API key. | Demo key |
| clusterId | Required, Your API key's cluster ID. | demo |
| 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., Ethreum main network. Set to true for Rinkeby test network. |
false |
| blockchainGasFee | Gas fee to set on Ethreum contract calls | 41000 |
Development
- 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 WebSocket docs