HTML5 - SPLessons
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. [html] var Socket = new WebSocket [/html] 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. [html] <script> // Create a WebSocket Connection var socket= new WebSocket("ws://www.example.com/webSocketserver.php"); </script> [/html] 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. [html] Socket.send(“some message ! ”); [/html] [html] <script> // Create a WebSocket Connection var socket= new WebSocket("ws://www.example.com/webSocketserver.php"); //Send your message using method send(). socket.send("Message"); /*WebSockets accept only plain text, hence complex data can be serialized using JSON strings.*/ var biodata = { Name: "Harry Potter", School: "Hogwarts ", Id: "Gryffindor0123" } socket.send(JSON.stringify(biodata)); </script> [/html] 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. [html] <script> // Create a WebSocket Connection var socket= new WebSocket("ws://www.example.com/webSocketserver.php"); // Web Socket is now connected. socket.close(); </script> [/html]

shape Examples

The code below demonstrates the over all working of web sockets by using all the methods. [html] <!DOCTYPE html> <html> <title>WebSocket</title> <style>body{font-family:Verdana; }</style> <script language="javascript" type="text/javascript"> var socket = "ws://echo.websocket.org/"; 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: ' + event.data+'</span>'); websocket.close(); } function onError(event) { writeToScreen('<span style="color: red;">ERROR:</span> ' + event.data); } function doSend(message) { writeToScreen("SENT: " + message); websocket.send(message); } function writeToScreen(message) { var temp = document.createElement("p"); temp.style.wordWrap = "break-word"; temp.innerHTML = message; output.appendChild(temp); } window.addEventListener("load", init, false); </script> <h2>HTML5 WebSocket Demo</h2> <div id="result"></div> </html> [/html] Result By running the above code in a preferred browser following output is obtained.

Summary

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.