Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

416 CHAPTER 10 WebSocket communications


that the client is waiting for data, and the server has an open connection. When data is ready,
it’s sent immediately, which results in decreased latency. One problem with this concept is
that connections can time out, which requires the creation of a new connection.

After this lesson, you will be able to:
■■Describe the WebSocket protocol.
■■Describe and implement the WebSocket object.

Estimated lesson time: 20 minutes

Understanding the WebSocket protocol


The WebSocket protocol provides a standardized way for the server to send content to the
browser without being solicited by the client and to allow messages to be passed back and
forth while keeping the connection open. A two-way (bidirectional), ongoing conversation
can take place between a browser and the server.
The WebSocket protocol is designed to be implemented in web browsers and web servers,
but any client or server application can use it. The protocol is an independent, TCP-based
protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as a
request to switch to WebSocket protocol. Each frame of WebSocket protocol has only 2 bytes
of overhead, and there are no headers. The light weight of the WebSocket protocol enables
more interaction between a browser and a website. This performance makes the WebSocket
protocol an easy choice for communicating when it’s necessary to deliver live content and
create real-time games.

Defining the WebSocket API


The W3C is responsible for defining the WebSocket API; as mentioned, the API is in work-
ing draft status at the time of this writing. This means that the W3C could make many more
changes before the API becomes a recommendation. However, the latest versions of Internet
Explorer, Google Chrome, Firefox, Opera, and Safari support WebSocket.
At the heart of the WebSocket API is the WebSocket object, which is defined on the win-
dow object. You can easily test whether this object exists to determine whether the browser
supports WebSocket. The WebSocket object contains the following members.
■■WebSocket constructor A method that requires a URL argument and can optionally
accept additional parameters to define the sub-protocol that you’ll use, such as chat or
rpc. The client and the server are typically matched to use the same protocol.
■■close A method that closes WebSocket.
■■send A method that sends data to the server.
Free download pdf