HTML5 - SPLessons

HTML5 WebSocket

Chapter 18

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

HTML5 WebSocket

HTML5 WebSocket

shape Introduction

HTML5 WebSocket are used to get the bi-directional connection with a server over a single connection. Following are the topics covered.

  • What are Websockets
  • Websocket vs HTTP
  • Browser Support
  • Using of WebSocket

What are Websockets

shape Description

WebSockets are the additional features of the HTML5 which makes the web server to directly communicate with the web browser without any delay and is known as bidirectional communication.

In between Web Server and Web browser there is a regular communication in the form of request and response as shown in the below image which is not present in the real time web applications.

WebSockets is used to establish the connection once.Communication between the webserver and web browser is useful to get any regular updates quickly.

Websocket vs HTTP

shape Description

In between the WebSocket and HTTP, size is the main issue. For example, in a real time application communincation between the client and server is necessary. If client sends a single request of information with HTTP, the HTTP header will send hundreds of bytes of information. But a socket would have only 2 bytes to frame the data as shown below.

Browser Support

shape Description

HTML5 Web Workers API supported by all the latest browsers.Following are the browser versions supported by HTML5.

Using of WebSocket

shape Description

In order to use the WebSocket, initially get the connection and later there are some methods to demonstrate the webSocket those are described below.

WebSocket Connection

shape Description

In order to carry out the Request-Response model communication, use the HTTP protocol for which web sockets are using TCP/IP protocol. TCP/IP protocol significant is less when compared to HTTP protocol because TCP/IP layer is present below HTTP layer.

Schemes for the HTTP protocol are http:// or http:// and for WebSockets ws:// or wss://

To set the WebSocket connection user need to use the WebSocket () constructor.

var Socket = new WebSocket

The argument of the WebSocket() is used as a URL for the host connections and port numbers. The protocol ws:// or wss:// is used for this connections.

	// Create a WebSocket Connection
	var socket= new WebSocket("ws://");

In order get the current state use the readyState attribute which can assume 4 values as shown below.

Value Numeric valiue Description
CONNECTING 0 Used to openning a connction
OPEN 1 Used to a connction opened
CLOSING 2 Used to openning a connction
CLOSED 3 Used to a connction closed

send() method

shape Description

After the connection gets established send the messages using the send() method.

Socket.send(“some message ! ”);
	// Create a WebSocket Connection 
	var socket= new WebSocket("ws://");
	//Send your message using method send().
	/*WebSockets accept only plain text, hence
	complex data can be serialized using JSON strings.*/ 
	var biodata = {
	Name: "Harry Potter",
	School: "Hogwarts ",
	Id: "Gryffindor0123"

The four types of events are used to handle the WebSockets when they get connected.

Event Handler Description
onopen Is get into action when the WebSocket connection is established.
onclose Is get into action when the WebSocket connection is closed
onerror Is get into action when Error occured
onmessage Is get into action when server send a message to the client

close() method

shape Description

User can close the connection between client and server by using the close() method the code is as shown below.

	// Create a WebSocket Connection 
	var socket= new WebSocket("ws://");
	// Web Socket is now connected.

shape Examples

The code below demonstrates the over all working of web sockets by using all the methods.

<!DOCTYPE html>
	<style>body{font-family:Verdana; }</style>
	<script language="javascript" type="text/javascript">
		var socket = "ws://";
		var output;
		function init() { 
		output = document.getElementById("result"); 
		DemoWebSocket(); } 
		function DemoWebSocket()
		websocket = new WebSocket(socket);
		//Event handler for open
		websocket.onopen = function(event)
		{ onOpen(event) };
		//Event handler for close 
		websocket.onclose = function(event)
		{ onClose(event) };
		//Event handler for message
		websocket.onmessage = function(event)
		{ onMessage(event) }; 
		//Event handler for error
		websocket.onerror = function(event) 
		{ onError(event) }; }

		// Function for respective event    
		function onOpen(event) 
		{ writeToScreen("WEBSOCKET CONNECTED");
		doSend("WebSocket is Awesome "); } 
		function onClose(event)
		{ writeToScreen("WEBSOCKET DISCONNECTED"); } 
		function onMessage(event)
		writeToScreen('<span style="color:#0000FF;">RESPONSE: ' 
		websocket.close(); }  
		function onError(event) { writeToScreen('<span style="color: red;">ERROR:</span> '
		function doSend(message)
		{ writeToScreen("SENT: " + message);
		websocket.send(message); }  
		function writeToScreen(message)
		{ var temp = document.createElement("p"); = "break-word"; 
		temp.innerHTML = message; output.appendChild(temp); 
		window.addEventListener("load", init, false);
	<h2>HTML5 WebSocket Demo</h2>
	<div id="result"></div>

By running the above code in a preferred browser following output is obtained.


shape Points

  • WebSockets have the full duplex, bi directional connection.
  • Web sockets are establish the connections only once.
  • By using the HTTP protocol user can exchange the packets quickly.