Introduction to WebSockets
API that creates a new WebSocket object
var socket = new WebSocket(url1, [protocol]);
- Websockets are a next-generation bidirectional communication technology used for web applications operating over a single socket.
- 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.
specifies the URL which is needed to be connected.
it is optional but if it is present it specifies a sub-protocol that the server supports for the connection to be successful.
WebSocket AttributesThe attributes of the WebSocket object are as follows:
1. Socket.readyState –
readyState represents the state of the connection. It can have the following values:
- indicates that the connection is not established.
- indicates that the connection is established and communication is possible.
- indicates that the connection is going through the closing handshake.
- 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 EventsThe events associated with the WebSocket object are as follows:
|open||Socket.onopen||When the socket connection is established this event will occur.|
|message||Socket.onmessage||When client receives data from the server this event will occur.|
|error||Socket.onerror||When there is any error in communication this event will occur.|
|close||Socket.onclose||When the connection is closed this event will occur.|
WebSocket MethodsThe 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.