HTML and CSS Reference
In-Depth Information
Listing 2-1. Sample WebSocket Constructor
// Create new WebSocket connection
var ws = new WebSocket(" ws:// " );
When connecting to a WebSocket server, you can optionally use the second
argument to list the protocols your application supports, namely for protocol negotiation.
To ensure that the client and the server are sending and receiving messages they
both understand, they must use the same protocol. The WebSocket constructor enables
you to define the protocol or protocols that your client can use to communicate with
a server. The server in turn selects the protocol to use; only one protocol can be used
between a client and a server. These protocols are used over the WebSocket Protocol. One
of the great benefits of WebSocket, as you'll learn in Chapters 3 through 6, is the ability
to layer widely used protocols over WebSocket, which lets you do great things like take
traditional desktop applications to the Web.
The WebSocket Protocol (RFC 6455) refers to protocols you can use with
WebSocket as “subprotocols,” even though they are higher-level, fully formed protocols.
Throughout this topic, we'll generally refer to protocols that you can use with WebSocket
simply as “protocols” to avoid confusion.
Before we get too far ahead of ourselves, let's return to the WebSocket constructor in
the API. During the initial WebSocket connection handshake, which you'll learn more
about in Chapter 3, the client sends a Sec-WebSocket-Protocol header with the protocol
name. The server chooses zero or one protocol and responds with a Sec-WebSocket-Protocol
header with the same name the client requested; otherwise, it closes the connection.
Protocol negotiation is useful for determining which protocol or version of a protocol
a given WebSocket server supports. An application might support multiple protocols and
use protocol negotiation to select which protocol to use with a particular server. Listing 2-2
shows the WebSocket constructor with support for a hypothetical protocol, “myProtocol”:
Listing 2-2. Sample WebSocket Constructor with Protocol Support
// Connecting to the server with one protocol called myProtocol
var ws = new WebSocket(" ws:// " , "myProtocol" );
In Listing 2-2, the hypothetical protocol “myProtocol” is a well-defined, perhaps
even registered and standardized, protocol name that both the client application and the
server can understand.
Search WWH ::

Custom Search