HTML and CSS Reference
In-Depth Information
Chapter 2
The WebSocket API
This chapter introduces you to the WebSocket Application Programming Interface (API),
which you can use to control the WebSocket Protocol and create WebSocket applications.
In this chapter, we examine the building blocks of the WebSocket API, including its events,
methods, and attributes. To learn how to use the API, we write a simple client application,
connect to an existing, publicly available server ( http://websocket.org ), which allows us
to send and receive messages over WebSocket. By using an existing server, we can focus
on learning about the easy-to-use API that enables you to create WebSocket applications.
We also explain step-by-step how to use the WebSocket API to power HTML5 media using
binary data. Finally, we discuss browser support and connectivity.
This chapter focuses on the client application side of WebSocket, which enables you
to extend the WebSocket Protocol to your web applications. The subsequent chapters
will describe the WebSocket Protocol itself, as well as using WebSocket within your
environment.
Overview of the WebSocket API
As we mentioned in Chapter 1, WebSocket consists of the network protocol and an API
that enable you to establish a WebSocket connection between a client application and the
server. We will discuss the protocol in greater detail in Chapter 3, but let's first take a look
at the API.
The WebSocket API is an interface that enables applications to use the WebSocket
Protocol. By using the API with your applications, you can control a full-duplex
communication channel through which your application can send and receive messages.
The WebSocket interface is very straightforward and easy to use. To connect to a remote
host, you simply create a new WebSocket object instance and provide the new object with
a URL that represents the endpoint to which you wish to connect.
A WebSocket connection is established by upgrading from the HTTP protocol to
the WebSocket Protocol during the initial handshake between the client and the server,
over the same underlying TCP connection. Once established, WebSocket messages can
be sent back and forth between the methods defined by the WebSocket interface. In your
application code, you then use asynchronous event listeners to handle each phase of the
connection life cycle.
The WebSocket API is purely (and truly) event driven. Once the full-duplex
connection is established, when the server has data to send to the client, or if resources
that you care about change their state, it automatically sends the data or notifications.
 
Search WWH ::




Custom Search