Using Apache Pulsar WebSockets for Real-Time Messaging in Front-End Applications

Tim Spann
2 min readFeb 3, 2022

--

Let’s build a single-page application with basic HTML, JavaScript, CSS, WebSockets and an Apache Pulsar cluster for sending, processing and receiving JSON messages in real-time.

Let’s build our web page utilizing JQuery and DataTables.

Web Page CSS and JS

<link rel=”stylesheet” type=”text/css” href=”https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">

<script type=”text/javascript” language=”javascript” src=”https://code.jquery.com/jquery-3.5.1.js"></script>

<script type=”text/javascript” language=”javascript” src=”https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>

Below is the page rendered and running in Chrome on my Mac.

Example Web Page
HTML Form For Chat Input
Send Chat Data on Submit
Build Pulsar Payload with JSON and Correctly Formats For Sending to Pulsar
Consume From public tenant, default namespace, chatresult2 topic via WebSockets
Loop through all the event from the Pulsar Topic and add as rows with columns to the dynamic table
Table to Format Our Data (Top and Bottom)
JavaScript to Check for Nulls and Valid JSON
Load the WebSocket Data When Ready

We need to extract and convert the data that is consumed from the Apache Pulsar topic. It is very easy in JavaScript.

websocket.onmessage = function(evt) {

var dataPoints = JSON.parse(evt.data);

var pulsarMessage = JSON.parse(atob(dataPoints.payload));

pulsarMessage.sentiment;

We receive the evt, parse it into JSON. We then pull out the payload field and turn it into plain text and then parse that JSON. This gives us pulsarMessage a number of fields such as sentiment.

Server Statistics Running Apache Pulsar Cluster, Pulsar SQL and Web Application

--

--

Tim Spann

Principal Developer Advocate, Zilliz. Milvus, Attu, Towhee, GenAI, Big Data, IoT, Deep Learning, Streaming, Machine Learning. https://www.datainmotion.dev/