The HTML5 WebSocket Object
The HTML5 WebSocket is bi-directional communication protocol which allows communication over a single socket. It is exposed via JavaScript Interface and only works with the HTML5 compliant browsers.
The HTML5 WebSocket Object has several attributes, methods and events which make WebSocket useful for building online application.
In order to create the HTML5 WebSocket we declare variable and and assign new WebSocket object to it.
<script>
//url specifies site we want to connect to and protocol is optional
var mySocketObject = new WebSocket(url, [protocal]);
</script>
There are two WebSocket Attributes. Let us examine these attributes in details:
Attribute |
Description |
Socket.readyState |
It represents the state of the HTML5 WebSocket connection with values ranging from 0 to 3. |
Socket.bufferedAmount |
It represents the number of bytes beening queued |
The HTML5 WebSocket events are available to you once you create WebSocket object as explained above. There are several events available:
Event Handler |
Description |
Socket.onopen |
It fires when connection is established |
Socket.onmessage |
It fires when data from the server is received by the client |
Socket.onerror |
It fires when error occur |
Socket.onclose |
It fires when connection is being closed |
The HTML5 WebSocket object has two distinct methods. These methods are:
Method |
Description |
Socket.send() |
It sends data using WebSocket connection |
Socket.close() |
It termines WebSocket existing connection |