CometD Java Client Subscription
Java CometD Client API: Subscribing and Unsubscribing
Subscription and unsubscription is done very similarly to the JavaScript counterpart explained here.
The Java API is only slightly different since it must register a MessageListener before subscribing to a channel:
public class Example
{
private static final String CHANNEL = "/foo";
private final MessageListener fooListener = new FooListener();
public void attach()
{
HttpClient httpClient = ...
BayeuxClient client = new BayeuxClient(httpClient, "http://localhost:8080/cometd");
client.start();
client.addListener(fooListener);
client.subscribe(CHANNEL);
}
private static class FooListener implements MessageListener
{
public void deliver(Client from, Client to, Message message)
{
if (CHANNEL.equals(message.getChannel())
{
// Here we received a message on the channel
}
}
}
}
Note
Calling subscribe() does not mean that you have completed the subscription with the server when subscribe() returns.
Differently from JavaScript, a MessageListener is notified for any type of channel (hence for meta channels as well as for normal channels).
Similarly, subscribe() only works properly for normal channels.
Unsubscription is straightforward: if you unsubscribe, messages on that channel will not be delivered to message listeners.
Using the Example class above:
public class Example
{
...
public void detach()
{
client.removeListener(fooListener);
client.unsubscribe(CHANNEL);
}
}
Tip
It is recommended that you remove also the MessageListener that you registered when you subscribed.
To make this simpler, avoid using the anonymous inner class style to register a message listener, since otherwise you will not have its reference when you want to remove it.
- Printer-friendly version
- Login to post comments