Creating a Java-Based Real-Time Push Server Using CometD

Vihan Pamudya Gammanpila
4 min readJan 23, 2024

by Vihan Gammanpila / January 23, 2024

Real-time communication is vital for today’s web applications, offering users immediate updates and alerts for a smooth experience. Setting up a push server is key for developing these real-time apps. In this article, we will discuss the process of establishing a real-time push server with CometD, a widely-used open-source version of the Bayeux protocol, using Java. We will also examine CometD alongside various web push protocols to evaluate its advantages and limitations in various use cases.

What is CometD?

CometD, an open-source version of the Bayeux protocol, enables real-time client-server communication. It provides a scalable and effective way to construct push servers, making it suitable for applications needing instant updates, like chat applications, remote applications, and real-time dashboards.

Building a Real-time Push Server with CometD

We’ll begin by creating a Maven project and launching a basic push server with CometD on Apache Tomcat. Step-by-step instructions with code examples will guide you through the process. This blog will address areas like developing a push server servlet, setting up the web application, and implementing it on Tomcat.

How to use?

Essential Requirements:

  • Installation of the Java Development Kit (JDK) on your computer.
  • Apache Tomcat set up on your machine.

Getting Started:

Step 1: Initialize the Maven Project

Begin by creating a new Maven project or utilizing an existing one. Ensure that your Maven dependencies include the CometD libraries. To do this, insert the following dependency into your project’s pom.xml file.

<dependencies>
<dependency>
<groupId>org.cometd.java</groupId>
<artifactId>cometd-java-server</artifactId>
<version>4.1.4</version>
</dependency>
</dependencies>

Step 2: Establish the Push Server Servlet

Initiate a new Java class, for example, PushServerServlet, which should extend from org.cometd.bayeux.server.BayeuxServlet. This servlet is responsible for managing client connections and processing messages.

import javax.servlet.annotation.WebServlet;
import org.cometd.annotation.ServerAnnotationProcessor;
import org.cometd.annotation.Service;
import org.cometd.annotation.Session;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.BayeuxServer.Channel;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.server.AbstractService;

@WebServlet("/push/*")
public class PushServerServlet extends org.cometd.bayeux.server.BayeuxServlet {
private static final long serialVersionUID = 1L;

@Service
public static class PushService extends AbstractService {
@Session
private ServerSession serverSession;

public PushService(BayeuxServer bayeux) {
super(bayeux, "push");
}

@org.cometd.annotation.Listener("/hello")
public void processHello(ServerSession remote, ServerMessage message) {
String name = (String) message.getDataAsMap().get("name");
System.out.println("Received hello from: " + name);
remote.deliver(serverSession, "/hello", "Hello, " + name + "!");
}
}

@Override
public void init() {
super.init();
BayeuxServer bayeux = (BayeuxServer) getServletContext().getAttribute(BayeuxServer.ATTRIBUTE);
new ServerAnnotationProcessor(bayeux).processAnnotations(PushService.class);
}
}

Step 3: Set Up the Web Application

Construct a web.xml file within the WEB-INF folder of your project. In this file, set up the CometD servlet along with its mapping as detailed below:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>CometD Push Server Example</display-name>

<servlet>
<servlet-name>PushServerServlet</servlet-name>
<servlet-class>com.example.PushServerServlet</servlet-class>
<init-param>
<param-name>transports</param-name>
<param-value>org.cometd.websocket.server.WebSocketTransport</param-value>
</init-param>
<async-supported>true</async-supported>
</servlet>

<servlet-mapping>
<servlet-name>PushServerServlet</servlet-name>
<url-pattern>/push/*</url-pattern>
</servlet-mapping>
</web-app>

Step 4: Launch the Application on Tomcat

Compile your Maven project and package it into a WAR file. Then, deploy this WAR file onto Apache Tomcat.

Step 5: Verify the Functionality of the Push Server

With your push server now active, it’s time to test it by linking clients to it. For instance, using JavaScript, you could construct a basic HTML page incorporating the code below:

<!DOCTYPE html>
<html>
<head>
<title>CometD Push Client</title>
<script src="/cometd.js"></script>
<script>
const cometd = new CometD();
cometd.configure({
url: location.protocol + "//" + location.host + "/push",
logLevel: "debug"
});
cometd.handshake();

cometd.addListener("/hello", function (message) {
console.log("Received: " + message.data);
});

function sendHello() {
const name = document.getElementById("name").value;
cometd.publish("/hello", { name: name });
}
</script>
</head>
<body>
<input type="text" id="name" placeholder="Your Name">
<button onclick="sendHello()">Send Hello</button>
</body>
</html>

This HTML page establishes a connection to the push server and dispatches a “hello” message including the given name. In response, the push server will send back a greeting message and record the names it receives on the server side.

Comparison with Other Web Push Protocols

To fully grasp CometD’s role in real-time communication, we will examine it alongside other notable web push protocols:

a. WebSockets: This widely used protocol facilitates a two-way, full-duplex communication link between clients and servers. It maintains a continuous connection, enabling swift data exchange with minimal delay.

b. Server-Sent Events (SSE): SSE is a web push technology that permits servers to push data updates to clients via a single, long-lasting HTTP connection. It’s particularly effective in situations where clients predominantly receive updates from the server.

c. MQTT (Message Queuing Telemetry Transport): MQTT is a streamlined messaging protocol tailored for environments with limited bandwidth and high latency, often used in IoT contexts to transfer data efficiently.

Summary

CometD stands out as a reliable and adaptable option for fulfilling the real-time communication demands of Java-driven web applications. Its simplicity in setup, ability to scale, and support for two-way communication render it highly suitable for a variety of scenarios. Whether it’s about deploying CometD within a self-managed setting or utilizing CometD Cloud for streamlined operations, developers are empowered to craft interactive, real-time user experiences.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vihan Pamudya Gammanpila
Vihan Pamudya Gammanpila

Written by Vihan Pamudya Gammanpila

Undergraduate of University of Moratuwa, Sri Lanka

No responses yet

Write a response