HTML and CSS Reference
With an event-driven API, you do not need to poll the server for the most updated
status of the targeted resource; rather, the client simply listens for desired notifications
We will see different examples of using the WebSocket API in the subsequent
chapters when we talk about higher-level protocols, such as STOMP and XMPP. For
now, though, let's take a closer look at the API.
Getting Started with the WebSocket API
The WebSocket API enables you to establish full-duplex, bidirectional communication
over the Web between your client application and server-side processes. The WebSocket
interface specifies the methods that are available for the client and how the client
interacts with the network.
To get started, you first create a WebSocket connection by calling the WebSocket
constructor. The constructor returns a WebSocket object instance. You can listen for
events on that object. These events tell you when the connection opens, when messages
arrive, when the connection closes, and when errors occur. You can interact with the
WebSocket instance to send messages or close the connection. The subsequent sections
explore each of these aspects of the WebSocket API.
The WebSocket Constructor
To establish a WebSocket connection to a server, you use the WebSocket interface to
instantiate a WebSocket object by pointing to a URL that represents the endpoint to which
you want to connect. The WebSocket Protocol defines two URI schemes, ws and wss for
unencrypted and encrypted traffic between the client and the server, respectively. The
ws (WebSocket) scheme is analogous to an HTTP URI scheme. The wss (WebSocket
Secure) URI scheme represents a WebSocket connection over Transport Layer Security
(TLS, also known as SSL), and uses the same security mechanism that HTTPS uses to
secure HTTP connections.
We'll discuss WebSocket security in depth in Chapter 7.
The WebSocket constructor takes one required argument, URL (the URL to which you
want to connect) and one optional argument, protocols (either a single protocol name
or an array of protocol names that the server must include in its response to establish the
connection). Examples of protocols you can use in the protocols argument are XMPP
(Extensible Messaging and Presence Protocol), SOAP (Simple Object Access Protocol), or
a custom protocol.
Listing 2-1 illustrates the one required argument in the WebSocket constructor,
which must be a fully qualified URL starting with the ws:// or wss:// scheme. In this
the URL, the constructor will throw an exception.