Skip navigation.

CometD JavaScript Handshake

JavaScript CometD API: Handshake

The call to handshake() (or to init()) is the one that initiates the Bayeux communication with the Bayeux server.

The Bayeux handshake performs 2 tasks:

  • the client and the server negotiate the type of transport to use
  • once the transport is negotiated successfully, the server informs the client with the detailed timings of the requests

As with several methods of the JavaScript CometD API, it is an asynchronous method: it returns immediately, well before the Bayeux handshake steps have completed.

Calling handshake() does not mean that you have completed the handshake with the server when handshake() returns.

The handshake may fail for several reasons:

  • you mistyped the server URL
  • the transport could not be negotiated successfully
  • the server denied the handshake (for example, the authentication credentials were wrong)
  • the server crashed
  • there was a network failure

Therefore it is not a good idea to write this code:

// Configure and handshake

// Publish to a channel
cometd.publish('/foo', { foo: 'bar' });

It is not a good idea, because there is no guarantee that the call to publish() (which we cover in a later section) can actually succeed in contacting the Bayeux server.
Since the API is asynchronous, you have no way of knowing synchronously (i.e. by having handshake() return an error code or by throwing an exception) that the handshake failed.
Even if the handshake succeeds, you may still be "disconnected" from the Bayeux server, for example because the server crashed just after the successful handshake.

Fortunately there is a way to be notified about the details of the Bayeux protocol message exchange: by adding listeners to special channels (called meta channels).
This is explained in the section about subscriptions.