Using Apache Pulsar WebSockets for Real-Time Messaging in Front-End Applications
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.
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.