HTML5 WebSocket
WebSocket is a protocol that enables full-duplex communication over a single TCP connection, introduced with HTML5.
WebSocket simplifies data exchange between the client and server, allowing the server to push data to the client. In the WebSocket API, a browser and server only need to complete one handshake, after which a persistent connection is established for bidirectional data transmission.
In the WebSocket API, a handshake is performed by the browser and server, after which a fast channel is formed between them for direct data transmission.
Many websites use Ajax polling to implement push technology. Polling involves the browser making HTTP requests to the server at specific intervals (e.g., every second), and the server returning the latest data to the client's browser. This traditional model has significant drawbacks, such as continuous requests from the browser, with HTTP requests potentially containing lengthy headers where only a small portion is useful data, thus wasting bandwidth and resources.
The WebSocket protocol defined by HTML5 saves server resources and bandwidth more effectively and allows for real-time communication.
Browsers request to establish a WebSocket connection with the server via JavaScript, and once connected, data can be exchanged directly over the TCP connection.
After obtaining a WebSocket connection, you can send data to the server using the send() method and receive data from the server using the onmessage event.
The following API is used to create a WebSocket object:
var Socket = new WebSocket(url, [protocol]);
The first parameter in the code above, url
, specifies the connection URL. The second parameter, protocol
, is optional and specifies the accepted sub-protocol.
WebSocket Properties
Below are the properties of the WebSocket object. Assuming we have created a Socket
object using the code above:
Property | Description |
---|---|
Socket.readyState | The read-only readyState property indicates the connection status, with possible values: 0 - Connection not established. <br>1 - Connection established, ready for communication. <br>2 - Connection is closing. <br>3 - Connection is closed or couldn't be opened. |
Socket.bufferedAmount | The read-only bufferedAmount property represents the number of bytes of UTF-8 text that have been queued using send() but not yet transmitted. |
WebSocket Events
Below are the events related to the WebSocket object. Assuming we have created a Socket
object using the code above:
Event | Event Handler | Description |
---|---|---|
open | Socket.onopen | Triggered when the connection is established. |
message | Socket.onmessage | Triggered when the client receives data from the server. |
error | Socket.onerror | Triggered when an error occurs in communication. |
close | Socket.onclose | Triggered when the connection is closed. |
WebSocket Methods
Below are the methods related to the WebSocket object. Assuming we have created a Socket
object using the code above:
Method | Description |
---|---|
Socket.send() | Sends data using the connection. |
Socket.close() | Closes the connection. |
WebSocket Example
The WebSocket protocol is essentially a TCP-based protocol.
To establish a WebSocket connection, the client browser first sends an HTTP request to the server, which includes additional headers, notably "Upgrade: WebSocket", indicating a protocol upgrade request. The server parses these headers and responds, establishing a WebSocket connection. This connection remains open for data transmission until either the client or server closes it.
Client-Side HTML and JavaScript
Most modern browsers support the WebSocket() interface. You can test the example in browsers like Chrome, Mozilla, Opera, and Safari.
Contents of tutorialpro_websocket.html
:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("Your browser supports WebSocket!");
// Open a web socket
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Sending data");
alert("Data is being sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Data received...");
};
ws.onclose = function()
{
// Close websocket
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("Your browser does not support WebSocket!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
Installing pywebsocket
Before running the above program, we need to set up a WebSocket-supported server. Download mod_pywebsocket
from pywebsocket or use the git command:
git clone https://github.com/googlearchive/pywebsocket
mod_pywebsocket
requires a Python environment. It is an extension for Apache HTTP and can be installed as follows:
- Extract the downloaded file.
- Navigate to the
pywebsocket
directory. - Execute the commands:
$ python setup.py build $ sudo python setup.py install
View documentation:
$ pydoc mod_pywebsocket
Starting the Service
Execute the following command in the pywebsocket/mod_pywebsocket
directory:
$ sudo python standalone.py -p 9998 -w ../example/
This command starts a service on port 9998, using -w
to set the directory containing the handler echo_wsh.py
.
Now, you can open the previously created tutorialpro_websocket.html
file in Chrome. If your browser supports WebSocket, clicking "Run WebSocket" will show pop-up windows at each step of the process. After stopping the service, a "Connection is closed..." message will appear.