PieSocket Channels

Channels are realtime PubSub connections over WebSocket.

Channels are available for Web. To use Channels on Android, iOS, IoT or any other platform, you need to use the WebSocket API.

Features

  • Subscribe to events on client side
  • Publish events from server
  • Publish events from client with C2C feature.

Installation

To use Channels, you need to install PieSocketJS.

Yarn

yarn add piesocket-js

NPM

npm i piesocket-js

CDN

<script src="https://unpkg.com/piesocket-js@2"></script>

Subscribe On Frontend

You need to subscribe to a channel to create a Channel connection.

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 Channel Events

Listen to an event

piesocket.subscribe(channelId).then(channel => {

  //Channel connection is established
  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

Lifecycle events are triggered by the system, when a change occurs on the Channel connection.

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 Channel Events

When an event is published, all the clients listening to that event receive it and their registered callback functions are triggered.

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 } }
}

Code examples of this request is available for PHP, NodeJS, Ruby, Python, Java, and Go in the docs.

Example - Build A Serverless Chatroom

Channels are simple and scalable PubSub connections, that's it. What you do with that power is upto you.

Let's use Channels to build a realtime chatroom in under 15 minutes.

Create HTML Page

Start by creating a basic html file, say piechat.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Realtime Chatroom - PieSocket Channels</title>
</head>
<body>
    <!-- Basic Chatroom Starts -->

</body>

Add PieSocketJS

Add PieSocketJS into your page by adding the following script in the head tag.

<script src="https://unpkg.com/piesocket-js@2"></script>

The power of Channels is your now. This adds a global variable PieSocket in your page.

Initizialize PieSocket

Initizialize PieSocket by adding the following code snippet into a script tag, just before closing the body tag.

var username = prompt("Enter username");
var piesocket = new PieSocket({
    clusterId: 'YOUR_CLUSTER_ID',
    apiKey: 'YOUR_API_KEY',
    consoleLogs: true,
    notifySelf: true,
    presence: true,
    userId: username
});

Subscribe And Listen

We are ready to subscribe to a channel and listen to events, add the following code snippet below the previous one to subscribe to a channel, say my-chat.

piesocket.subscribe("my-chat").then(ch => {
    window.channel = ch;

    channel.listen("new-message", function (data, meta) {
        //Custom event, fired when new messages arrive
        document.getElementById("chat-log").innerHTML += '<div> '+data.from+': '+ data.message + '</div>';
    });

    channel.listen("system:member_joined", function (data, meta) {
        //Presence event, published by the system
        document.getElementById("chat-log").innerHTML += '<div> '+data.member.user+' joined</div>';
    });

    channel.listen("system:member_left", function (data, meta) {
        //Presence event, published by the system
        document.getElementById("chat-log").innerHTML += '<div> '+data.member.user+' left</div>';
    });
})

Add Chat UI

Add following HTML elements at the top of the body tag

<!-- Basic Chatroom Starts -->
<textarea id="chat-input"></textarea>
<div id="chat-log"></div>

Handle Chat Submit

Add the following code at the bottom of the script tag to publish messages directly from the client (C2C must be enabled for the API key) when Enter key is pressed in the textarea.

var chatInput = document.getElementById("chat-input");
chatInput.onkeyup = function (e) {
    if (e.keyCode == 13) {
        //Enter key is pressed, publish new-message event
        channel.publish("new-message", {
            message: chatInput.value,
            from: username
        });
        chatInput.value = "";
    }
}

Complete HTML File

Following is the complete HTML file.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Realtime Chatroom - PieSocket Channels</title>
    <script src="https://unpkg.com/piesocket-js@2"></script>
</head>

<body>
    <!-- Basic Chatroom Starts -->
    <textarea id="chat-input"></textarea>
    <div id="chat-log"></div>

    <script>
        var username = prompt("Enter username");
        var piesocket = new PieSocket({
            clusterId: 'YOUR_CLUSTER_ID',
            apiKey: 'YOUR_API_KEY',
            consoleLogs: true,
            notifySelf: true,
            presence: true,
            userId: username
        });

        piesocket.subscribe("my-chat").then(ch => {
            window.channel = ch;

            channel.listen("new-message", function (data, meta) {
                //Custom event, fired when new messages arrive
                document.getElementById("chat-log").innerHTML += '<div> ' + data.from + ': ' + data.message + '</div>';
            });

            channel.listen("system:member_joined", function (data, meta) {
                //Presence event, published by the system
                document.getElementById("chat-log").innerHTML += '<div> ' + data.member.user + ' joined</div>';
            });

            channel.listen("system:member_left", function (data, meta) {
                //Presence event, published by the system
                document.getElementById("chat-log").innerHTML += '<div> ' + data.member.user + ' left</div>';
            });
        });

        var chatInput = document.getElementById("chat-input");
        chatInput.onkeyup = function (e) {
            if (e.keyCode == 13) {
                //Enter key is pressed, publish new-message event
                channel.publish("new-message", {
                    message: chatInput.value,
                    from: username
                });
                chatInput.value = "";
            }
        }
    </script>
</body>

Save this file as piechat.html and open in multiple tabs of your browser. You should be able to chat with yourself through different tabs.

If you host the same file on a server and send the link to your friends, you should be able to chat with them in realtime.

Realtime Blockchain

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
});

User will have to sign this message using the MetaMask Ethereum Wallet.

Optinally, to confirm a message on the receiver's end i.e. 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 to the sender, after confirmation is successful.

To get a list of blockchain messages pending acceptance, use the REST API.

Help

Facing difficulties? Use the chat box on the bottom-right corner of this page to reach us.