HTML5 WebSockets

Introduction to WebSockets

  • Websockets are a next-generation bidirectional communication technology used for web applications operating over a single socket.
  • They are exposed via a JavaScript interface in HTML5 with compliant browsers.
  • Once a web socket is connected with the web server the data can be sent from the browser to the server by calling a send() method and data is received from server to browser by an onmessage event handler.
API that creates a new WebSocket object

var socket = new WebSocket(url1, [protocol]);

     URL – specifies the URL which is needed to be connected.
     protocol – it is optional but if it is present it specifies a sub-protocol that the server supports for the connection to be successful.

WebSocket Attributes

The attributes of the WebSocket object are as follows:

1. Socket.readyState – readyState represents the state of the connection. It can have the following values:

a) 0 - indicates that the connection is not established.
b) 1 - indicates that the connection is established and communication is possible.
c) 2 - indicates that the connection is going through the closing handshake.
d) 3 - indicates that the connection is closed or cannot be opened.

2. Socket.bufferedAmount – bufferedAmount will represent the number of bytes of UTF-8 text that is queued by using the send() method.

WebSocket Events

The events associated with the WebSocket object are as follows:

EventEvent HandlerDescription
openSocket.onopenWhen the socket connection is established this event will occur.
messageSocket.onmessageWhen client receives data from the server this event will occur.
errorSocket.onerrorWhen there is any error in communication this event will occur.
closeSocket.oncloseWhen the connection is closed this event will occur.

WebSocket Methods

The methods associated with the WebSocket object are as follows:

1. Socket.send() - Data is transmitted by using a connection in a send(data) method.
2. Socket.close() - Any existing connection is terminated by using the close() method.