Featured Image
Software Development

How to Use PubNub for Real-Time Communication: A Comprehensive Guide

Today, real-time communication has evolved into an indispensable feature, seamlessly integrated into the fabric of countless websites and mobile applications. Whether it’s e-commerce platforms or the domain of food delivery services, the provision of chat functionality has become a non-negotiable component.

Consider the instance of Zomato, where users can effortlessly engage with their delivery partners, or the dynamic world of BGMI, where real-time communication enriches the gaming experience by fostering interactive gameplay among enthusiasts. These instances underscore the pivotal role that chat plays in shaping the user experience of modern-day products, reiterating its significance as a critical cornerstone of these digital ecosystems.

However, the intricacies of implementing a robust chat mechanism are not to be overlooked. Addressing the complexities of reliability, message delivery speed, and scalability poses a significant challenge, potentially diverting valuable resources and attention away from core product development.

But what if I told you that the arduous process of building a chat system from scratch could be bypassed entirely? Imagine a hassle-free solution that eliminates the need to manage infrastructure and ensures the seamless functioning, scalability, and reliability of your chat service. Enter PubNub, a comprehensive tool that streamlines real-time messaging and other essential functionalities, serving as a one-stop destination for all your communication needs.

Overview of Series

In this upcoming blog series, we will delve into the intricate workings of PubNub, exploring its diverse functionalities and versatile use cases, accompanied by a thorough understanding of its core concepts. Our journey will encompass a comprehensive exploration of how PubNub can be leveraged to architect end-to-end personal 1:1 as well as group chat solutions.

Additionally, we will delve into configuring PubNub to enable push notifications for chat messages, enhancing the overall user experience by enabling customization of notification preferences. Brace yourself for an insightful exploration of how PubNub’s robust features can revolutionize the landscape of real-time communication within your product.

Note that throughout this blog series, our primary aim is to provide you with a comprehensive guide on effectively harnessing the full potential of PubNub’s rich array of features, enabling you to seamlessly integrate and optimize its functionalities within your product, especially for the use-case of 1:1 and group chatting. We will not cover the implementation in a specific programming language or framework. Implementations might differ according to the specific needs of the product. 

So, let’s get started with an introduction to PubNub!

Introduction to PubNub

PubNub is a highly-available, real-time communication platform optimized for maximum performance. You can use it to build chats, IoT Device Control systems, Geolocation & Dispatch apps, and many other communication solutions

PubNub provides the infrastructure and platform necessary for delivering any message in real-time. You can use it via SDKs provided by them to use their system for your application use case. They offer global scalability, 99.999% uptime SLA, and an extendable platform for new real-time use cases and third-party APIs.

Basic Working of PubNub

As shown in the figure, PubNub works on a client-server-based publish-subscribe mechanism. Clients can be anything from Web apps, Mobile Apps, or other devices. 

PubNub uses the concept of channels to transfer messages in real time. For a device/user to send, and receive the messages, it needs to subscribe to a specific channel.

Once subscribed, the device will need to set listeners provided by PubNub to listen for events in real-time and can handle them in real-time. Your backend server might also come into the picture to maintain the overall workflow per your use case.

The following figure shows the basic relationship between users and channels.

As shown in the figure, there can be multiple users and channels. For your system, a channel can represent any entity where messages are exchanged. For example, consider the following use cases.

Chatting mechanism for support in food delivery platforms

We can create one channel for each order. The user who placed an order and the support executives will subscribe to that channel. Users can post an order support query there. Support executives will receive those queries.

1:1/Group Chattings

We can create one channel for each 1:1 chat or chat group. In the case of 1:1 personal chat room, two users who are part of that chatroom will subscribe to that channel. In the case of group channels, all the users who become part of the group can subscribe to the group channel.

These examples give you a clear idea of how we can utilize PubNub. A few things to note about channels: 

  • Channels do not need to be created explicitly. You can start referring to any channel as if it was already present.
  • Subscribing to a channel to publish a message on it is unnecessary. However, it is mandatory to subscribe to the channel in order to receive published messages in real time.
  • It is recommended to have a consistent and meaningful naming convention for channels in your system.

To know more about channels, take a look at this section from the PubNub official documentation

Features of PubNub 

  • SDKs are available for all major programming languages
  • Real time messaging with a rich set of features like message persistence, fetching message history, message actions, file sharing, etc.
  • Push notifications integration with services like Apple Push, Firebase
  • PubNub Functions : – A serverless coding mechanism to handle events on the PubNub platform. Allows you to write code to handle events like message publish, before publish etc without worrying about the deployments of that code!
  • Guaranteed to deliver messages with <100ms latency

Getting Started With PubNub

Alright, how is this all going to work? Enough discussion; now let’s head straight into the action!

First thing first. Sign up on PubNub here and get access to the PubNub admin portal.

Next, create a new App. You can have multiple Apps in your account. When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. It is recommended that you create separate keysets for production and test environments. A keyset combines the publish key, the subscribe key, and a secret key. They are required to access PubNub functionalities via SDKs

Once you have created an App and access the necessary credentials, choose the appropriate SDK, and install it by following the steps given in the respective documentation for that SDK. 

Now, we will create a basic message send/receive app using the JavaScript SDK.

Demo application Demonstrating the basic Publish/Subscribe Mechanism using the JavaScript SDK(For NodeJS runtime)

Scenario: We have a common channel named “messaging_channel”. All messages will be published there and the receiver will subscribe to that channel and log messages on receiving them.

First, follow the steps mentioned in the Getting started section. Then, you will have the necessary configuration ready for going ahead

Creating an npm project and installing the PubNub SDK 

First, initiate an npm project called “PubNubDemo”. And install the pubnub sdk using the following command: 

npm install pubnub

Creating a file called receiver.js and adding the code snippet

const PubNub = require("pubnub")

// Initialize PubNub Instance with credentials and userId
const pubnub = new PubNub({
  publishKey: "<your_publish_key>",
  subscribeKey: "<your_subscribe_key>",
  secretKey: "<your_secret_key>",
  userId: "sendingUser",
})

// Initialize a listsner with event handlers
const listner = {
  // Event handler to handle incoming messages in real time.
  // Whenever any message is published, pubnub fires "message" event
  message: (message) => {
    // Handle message.
    const channelName = message.channel // The channel to which the message was published
    const messageTimeToken = message.timetoken // Publish timetoken
    const msg = message.message // The Payload

    console.log(
      `Message Received On Channel : ${channelName}, Timetoken: ${messageTimeToken}, Message: ${JSON.stringify(
        msg,
        null,
        4
      )}
Published by : ${message.publisher}`
    )
  },
}

// Add listener to pubnub instance
pubnub.addListener(listner)

// Subscribe to channel named "message_channel" where we are expecting messages to be published
pubnub.subscribe({
  channels: ["messaging_channel"],
})

Breaking down the code for receiver.js 

const PubNub = require("pubnub")

// Initialize PubNub Instance with credentuials and userId

const pubnub = new PubNub({
  publishKey: "<your_publish_key>",
  subscribeKey: "<your_subscribe_key>",
  secretKey: "<your_secret_key>",
  userId: "sendingUser",
})

The code above imports the PubNub SDK and creates a PubNub instance using credentials and userId. Replace your credentials at the appropriate place. 

Here, the userId field is very important. It is used to identify users in your app uniquely. We have named it “sendingUser” here for demo purposes. But it is recommended that you generate this randomly and it should be unique per user. You can store this user ID in your database and reuse it for existing users.

// Initialize a listsner with event handlers

const listner = {
  // Event handler to handle incoming messages in real time.

  // Whenever any message is published, pubnub fires "message" event

  message: (message) => {
    // Handle message.

    const channelName = message.channel // The channel to which the message was published

    const messageTimeToken = message.timetoken // Publish timetoken

    const msg = message.message // The Payload

    console.log(
      `Message Received On Channel : ${channelName}, Timetoken: ${messageTimeToken}, Message: ${JSON.stringify(
        msg
      )}
    
    Published by : ${message.publisher}`
    )
  },
}

// Add listener to pubnub instance

pubnub.addListener(listner)

Next, we set up a listener to handle a “message” event. Whenever any message is published on any channel, PubNub fires a message event. On receiving a message event, PubNub will execute the event handler. In our handler, We have simply logged the information received from PubNub, including the actual message payload. The last line registers the listeners on a pubnub instance. 

For more details on message receiving and different events available, see Receiving the message page from official documentation.

// Subscribe to channel named "message_channel" where we are expecting messages to be published

pubnub.subscribe({
  channels: ["messaging_channel"],
})

This is the most important part of the receiver code. To start receiving messages and events on channels, it is required to subscribe to those channels. In the above lines, we have called subscribe method and instructed the current PubNub instance to listen for events on a channel named “message_channel.” 

Note that you can subscribe to multiple channels in a single subscribe call. To know more about subscribing in detail, see the channel subscription section in the official documentation.

Now you can run the file “receiver.js” using the following command : 

node receiver.js

Once you run it, you will notice that the executed node script will go into listening mode and wait for any events.

Okay. Congratulations! You have successfully set up a message listener and it is ready to receive the messages. Now let’s write code for sending a message. 

Creating a file named sender.js and adding the code snippet

const PubNub = require("pubnub")

// Initialize PubNub Instance

const pubnub = new PubNub({
  publishKey: "<your_publish_key>",
  subscribeKey: "<your_subscribe_key>",
  secretKey: "<your_secret_key>",
  userId: "sendingUser",
})

// Publish a message on channel named “messaging_channel”

pubnub.publish(
  {
    channel: "messaging_channel",
    message: { text: "Hello World!" },
  },

  function (status, response) {
    console.log(status)
    console.log(response)
  }
)

Breaking down the code for sender.js

Focus on the publish call on the pubnub instance in the above code. It simply instructs the instance to publish a message on a channel named “messaging_channel.” The publish call pushes the specified message on a given channel, and it triggers a “message” event on that channel.

Note that the “message” parameter here can be any JSON Object. There is no fixed format for it. It can be any object with custom key-value pairs. To know more about publishing a message in detail, see the message publish section in the official documentation.

Running the sender and receiver scripts

Run this file using the following command in a separate terminal using the following command : 

node sender.js

Make sure that the receiver.js script is running before running sender.js. 

If you have followed all steps as instructed, you will see the following output on the receiver side : 

Message Received On Channel : message_channel, Timetoken: 16993692086868389, Message: {“text”: “Hello World!”} Published by : sendingUser

Hooray! we just set up our first sender and receiver scripts using PubNub sdk. 

Also read: Learn How to Use PubNub for Real-Time Chat in Your Flutter Projects

Conclusion 

We saw that real time chatting is an important part of modern web and mobile apps. Implementing chat from scratch introduces technical complexities and if we go to address those on our own, it might divert our focus from actual product’s implementation.

We saw how PubNub can be useful in such scenarios. We introduced the basic conceptual working of PubNub using channels, publish and subscribe concepts. 

We also wrote code for a simple sender and receiver using the Node SDK of PubNub.  

Now that we are familiar with the basic core concepts of PubNub like channels, publishing a message, subscribing to channels and receiving messages on channels, in the upcoming blog of the series, we will focus on how we can design 1:1 and group chatting workflow using these concepts. 

Want to build a real-time communication app with Node.js and PubNub? As a certified PubNub advanced tier integration partner, we can help you with that. Contact us for expert assistance.

We also have extensive experience in Node.js app development and software product development. Learn more about how we can help you achieve your goals.

author
Soham Patel
I am a software developer with keen interest in back-end development and DevOps. I am passionate about and have experience in understanding business requirements and translating those into efficient, well-maintainable and reliable software products.