HTML and CSS Reference
In-Depth Information
The WebSocket object
It's now time to initialize a connection to the server. All we need is to create a We-
bSocket JavaScript object, providing the URL to the remote or local server:
var socket = new
WebSocket("ws://echo.websocket.org");
When this object is constructed, it immediately opens a connection to the specified
server. Chapter 3 , Configuring the Server , will show us in detail how we can develop
the server-side program. For now, just keep in mind that a valid WebSocket URL is
necessary.
The example URL ws://echo.websocket.org is a public address that we can
use for testing and experiments. The Websocket.org server is always up and running
and, when it receives a message, it sends it back to the client! It's all we need in or-
der to ensure that our client-side application works properly.
Events
After creating the WebSocket object, we need to handle the events it exposes.
TherearefourmaineventsintheWebSocketAPI:Open,Message,Close,andError.
You can handle them either by implementing the onopen , onmessage , onclose ,
and onerror functions respectively, or by using the addEventListener method.
Both ways are almost equivalent for what we need to do, but the first one is much
clearer.
Note that, obviously, the functions we'll provide to our events will not be executed
consecutively. They will be executed asynchronously when a specific action occurs.
So, let's have a closer look at them.
onopen
The onopen event is raised right after the connection has been successfully estab-
lished. It means that the initial handshake between the client and the server has led
to a successful first deal and the application is now ready to transmit data:
Search WWH ::




Custom Search