Class BayeuxClient
- All Implemented Interfaces:
Bayeux, ClientSession, Session, org.eclipse.jetty.util.component.Dumpable
- Direct Known Subclasses:
OortComet
BayeuxClient is the implementation of a client for the Bayeux protocol.
A BayeuxClient can receive/publish messages from/to a Bayeux server, and it is the counterpart in Java of the JavaScript library used in browsers (and as such it is ideal for Swing applications, load testing tools, etc.).
A BayeuxClient handshakes with a Bayeux server
and then subscribes ClientSessionChannel.MessageListener to channels in order
to receive messages, and may also publish messages to the Bayeux server.
BayeuxClient relies on pluggable transports for communication with the Bayeux server.
When the communication with the server is finished, the BayeuxClient can be disconnected from the Bayeux server.
Typical usage:
// Setup Jetty's HttpClient.
HttpClient httpClient = new HttpClient();
httpClient.start();
// Handshake
String uri = "http://localhost:8080/cometd";
BayeuxClient client = new BayeuxClient(uri, new JettyHttpClientTransport(null, httpClient));
client.handshake();
client.waitFor(1000, BayeuxClient.State.CONNECTED);
// Subscription to channels
ClientSessionChannel channel = client.getChannel("/foo");
channel.subscribe((channel, message) -> {
// Handle the message
});
// Publishing to channels
Map<String, Object> data = new HashMap<>();
data.put("bar", "baz");
channel.publish(data);
// Disconnecting
client.disconnect();
client.waitFor(1000, BayeuxClient.State.DISCONNECTED);
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceA strategy to controls wait times of the retry attempts in case of heartbeat failures.protected classA channel scoped to this BayeuxClient.static classstatic enumThe states that a BayeuxClient may assume.Nested classes/interfaces inherited from class AbstractClientSession
AbstractClientSession.AbstractSessionChannelNested classes/interfaces inherited from interface Bayeux
Bayeux.BayeuxListener, Bayeux.ValidatorNested classes/interfaces inherited from interface ClientSession
ClientSession.Extension, ClientSession.MessageListenerNested classes/interfaces inherited from interface org.eclipse.jetty.util.component.Dumpable
org.eclipse.jetty.util.component.Dumpable.DumpableContainer -
Field Summary
FieldsFields inherited from interface org.eclipse.jetty.util.component.Dumpable
KEY -
Constructor Summary
ConstructorsConstructorDescriptionBayeuxClient(String url, ScheduledExecutorService scheduler, ClientTransport transport, ClientTransport... transports) Creates a BayeuxClient that will connect to the Bayeux server at the given URL, with the given scheduler and with the given transport(s).BayeuxClient(String url, ClientTransport transport, ClientTransport... transports) Creates a BayeuxClient that will connect to the Bayeux server at the given URL and with the given transport(s). -
Method Summary
Modifier and TypeMethodDescriptionvoidabort()Interrupts abruptly the communication with the Bayeux server.voidaddTransportListener(TransportListener listener) booleandisconnect(long timeout) Performs adisconnectand uses the giventimeoutto wait for the disconnect to complete.voiddisconnect(ClientSession.MessageListener callback) Disconnects this session, ending the link between the client and the server peers.protected voidenqueueSend(Message.Mutable message) org.eclipse.jetty.http.HttpCookieRetrieves the first cookie with the given name, if available.org.eclipse.jetty.http.HttpCookieStoregetId()The clientId of the session.protected BayeuxClient.StategetState()getTransport(String transport) getURL()handshake(long waitMs) Performs the handshake and waits at most the given time for the handshake to complete.Performs the handshake with the given template and waits at most the given time for the handshake to complete.voidhandshake(Map<String, Object> fields, ClientSession.MessageListener callback) Initiates the bayeux protocol handshake with the server(s).voidhandshake(ClientSession.MessageListener callback) protected voidbooleanA connected session is a session where the link between the client and the server has been established.booleanbooleanA handshook session is a session where the handshake has successfully completedprotected voidmessagesFailure(Throwable cause, List<? extends Message> messages) newChannel(ChannelId channelId) protected ChannelIdnewChannelId(String channelId) protected voidonTransportFailure(String oldTransportName, String newTransportName, Throwable failure) protected voidonTransportFailure(Message message, ClientTransport.FailureInfo failureInfo, ClientTransport.FailureHandler handler) protected voidprocessConnect(Message.Mutable connect) protected voidprocessDisconnect(Message.Mutable disconnect) protected voidprocessHandshake(Message.Mutable handshake) protected voidprocessMessage(Message.Mutable message) voidputCookie(org.eclipse.jetty.http.HttpCookie cookie) voidremoveTransportListener(TransportListener listener) protected booleanscheduleConnect(long interval, long backOff) protected booleanscheduleHandshake(long interval, long backOff) protected voidsend(Message.Mutable message) protected voidprotected voidprotected voidprotected voidsendMessages(List<Message.Mutable> messages, Promise<Boolean> promise) voidsetBackOffStrategy(BayeuxClient.BackOffStrategy backOffStrategy) voidprotected voidtoString()booleanwaitFor(long waitMs, BayeuxClient.State state, BayeuxClient.State... states) Waits for this BayeuxClient to reach the given state(s) within the given time.Methods inherited from class AbstractClientSession
addExtension, batch, dump, endBatch, extendIncoming, extendOutgoing, getAttribute, getAttributeNames, getChannel, getChannel, getChannels, getExtensions, isBatching, newMessage, newMessageId, notifyCallback, notifyListeners, receive, registerCallback, registerSubscriber, remoteCall, removeAttribute, removeExtension, resetSubscriptions, setAttribute, startBatch, unregisterCallback, unregisterSubscriberMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface ClientSession
disconnect, handshake, handshakeMethods inherited from interface org.eclipse.jetty.util.component.Dumpable
dump, dumpSelf
-
Field Details
-
BACKOFF_INCREMENT_OPTION
- See Also:
-
MAX_BACKOFF_OPTION
- See Also:
-
BAYEUX_VERSION
- See Also:
-
-
Constructor Details
-
BayeuxClient
Creates a BayeuxClient that will connect to the Bayeux server at the given URL and with the given transport(s).
This constructor allocates a new
scheduler; it is recommended that when creating a large number of BayeuxClients a shared scheduler is used.- Parameters:
url- the Bayeux server URL to connect totransport- the default (mandatory) transport to usetransports- additional optional transports to use in case the default transport cannot be used- See Also:
-
BayeuxClient
public BayeuxClient(String url, ScheduledExecutorService scheduler, ClientTransport transport, ClientTransport... transports) Creates a BayeuxClient that will connect to the Bayeux server at the given URL, with the given scheduler and with the given transport(s).
- Parameters:
url- the Bayeux server URL to connect toscheduler- the scheduler to use for scheduling timed operationstransport- the default (mandatory) transport to usetransports- additional optional transports to use in case the default transport cannot be used
-
-
Method Details
-
getURL
- Returns:
- the URL passed when constructing this instance
-
getBackOffStrategy
-
setBackOffStrategy
-
getHttpCookieStore
public org.eclipse.jetty.http.HttpCookieStore getHttpCookieStore() -
getCookie
Retrieves the first cookie with the given name, if available.
Note that currently only HTTP transports support cookies.
- Parameters:
name- the cookie name- Returns:
- the cookie, or null if no such cookie is found
- See Also:
-
putCookie
public void putCookie(org.eclipse.jetty.http.HttpCookie cookie) -
getId
Description copied from interface:SessionThe clientId of the session.
This would more correctly be called a "sessionId", but for backwards compatibility with the Bayeux protocol, it is a field called "clientId" that identifies a session.
-
isHandshook
public boolean isHandshook()Description copied from interface:SessionA handshook session is a session where the handshake has successfully completed
- Specified by:
isHandshookin interfaceSession- Returns:
- whether the session is handshook
-
isConnected
public boolean isConnected()Description copied from interface:SessionA connected session is a session where the link between the client and the server has been established.
- Specified by:
isConnectedin interfaceSession- Returns:
- whether the session is connected
- See Also:
-
isDisconnected
public boolean isDisconnected()- Returns:
- whether this BayeuxClient is terminating or disconnected
-
getState
- Returns:
- the current state of this BayeuxClient
-
addTransportListener
- Parameters:
listener- theTransportListenerto add
-
removeTransportListener
- Parameters:
listener- theTransportListenerto remove
-
handshake
- Parameters:
callback- the message listener to notify of the handshake result
-
handshake
Description copied from interface:ClientSessionInitiates the bayeux protocol handshake with the server(s).
The handshake initiated by this method is asynchronous and does not wait for the handshake response.
- Specified by:
handshakein interfaceClientSession- Parameters:
fields- additional fields to add to the handshake message.callback- the message listener to notify of the handshake result
-
handshake
Performs the handshake and waits at most the given time for the handshake to complete.
When this method returns, the handshake may have failed (for example because the Bayeux server denied it), so it is important to check the return value to know whether the handshake completed or not.
- Parameters:
waitMs- the time to wait for the handshake to complete- Returns:
- the state of this BayeuxClient
- See Also:
-
handshake
Performs the handshake with the given template and waits at most the given time for the handshake to complete.
When this method returns, the handshake may have failed (for example because the Bayeux server denied it), so it is important to check the return value to know whether the handshake completed or not.
- Parameters:
template- the template object to be merged with the handshake messagewaitMs- the time to wait for the handshake to complete- Returns:
- the state of this BayeuxClient
- See Also:
-
sendHandshake
protected void sendHandshake() -
waitFor
Waits for this BayeuxClient to reach the given state(s) within the given time.
- Parameters:
waitMs- the time to wait to reach the given state(s)state- the state to reachstates- additional states to reach in alternative- Returns:
- true if one of the state(s) has been reached within the given time, false otherwise
-
sendConnect
protected void sendConnect() -
newChannelId
- Specified by:
newChannelIdin classAbstractClientSession
-
newChannel
- Specified by:
newChannelin classAbstractClientSession
-
sendBatch
protected void sendBatch()- Specified by:
sendBatchin classAbstractClientSession
-
sendMessages
-
disconnect
Description copied from interface:ClientSessionDisconnects this session, ending the link between the client and the server peers.
- Specified by:
disconnectin interfaceClientSession- Parameters:
callback- the message listener to notify of the disconnect result
-
disconnect
public boolean disconnect(long timeout) Performs a
disconnectand uses the giventimeoutto wait for the disconnect to complete.When a disconnect is sent to the server, the server also wakes up the long poll that may be outstanding, so that a connect reply message may arrive to the client later than the disconnect reply message.
This method waits for the given
timeoutfor the disconnect reply, but also waits the same timeout for the last connect reply; in the worst case the maximum time waited will therefore be twice the giventimeoutparameter.This method returns true if the disconnect reply message arrived within the given
timeoutparameter, no matter if the connect reply message arrived or not.- Parameters:
timeout- the timeout to wait for the disconnect to complete- Returns:
- true if the disconnect completed within the given timeout
-
abort
public void abort()Interrupts abruptly the communication with the Bayeux server.
This method may be useful to simulate network failures.
- See Also:
-
messagesFailure
-
processHandshake
-
processConnect
-
processDisconnect
-
processMessage
-
scheduleHandshake
protected boolean scheduleHandshake(long interval, long backOff) -
scheduleConnect
protected boolean scheduleConnect(long interval, long backOff) -
getAllowedTransports
- Specified by:
getAllowedTransportsin interfaceBayeux- Returns:
- the ordered list of transport names that will be used in the negotiation of transports with the other peer.
- See Also:
-
getKnownTransportNames
- Specified by:
getKnownTransportNamesin interfaceBayeux- Returns:
- the set of known transport names of this Bayeux object.
- See Also:
-
getTransport
- Specified by:
getTransportin interfaceBayeux- Parameters:
transport- the transport name- Returns:
- the transport with the given name or null if no such transport exist
-
getTransport
-
initialize
protected void initialize() -
terminate
-
getOption
-
setOption
-
getOptionNames
- Specified by:
getOptionNamesin interfaceBayeux- Returns:
- the set of configuration options
- See Also:
-
getOptions
-
send
- Specified by:
sendin classAbstractClientSession
-
enqueueSend
-
onTransportFailure
protected void onTransportFailure(Message message, ClientTransport.FailureInfo failureInfo, ClientTransport.FailureHandler handler) -
onTransportFailure
-
toString
-