HTML and CSS Reference
The WebSocket object
It's now time to initialize a connection to the server. All we need is to create a We-
var socket = new
When this object is constructed, it immediately opens a connection to the specified
the server-side program. For now, just keep in mind that a valid WebSocket URL is
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.
After creating the WebSocket object, we need to handle the events it exposes.
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
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.
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: