HTML5 Websocket




HTML5 WebSocket

WebSocket helps in establishing a two-way interactive communication channel between client and server. In addition, With Websocket we can automatically transmit and receive continuous messages or data without having to ask the server for updates.

 

Creating a WebSocket connection

const socket = new WebSocket(<URI>);
URI - The WebSocket endpoint

On socket creation, we have 4 event handlers open, message, close, error.

HTML dropdown list

open event gets triggered once the socket handshake is a success.

socket.addEventListener('open', function (event) {
  socket.send('Hi Server!');
});

message event listener acts as a listener to server messages, triggered on receiving a message from the server.

socket.addEventListener('message', function (event) {
  console.log('Message from server ', event.data);
});

error event gets triggered on the occurrence of an error in the WebSocket

socket.addEventListener('error', function (error) {
   console.log('Error occured', error.message);
});

close event prompts close of WebSocket connection.

socket.addEventListener('close', function (event) {
   console.log('Connection closed',event.reason);
});

Sample code:

Most of the modern browsers support the WebSocket protocol. Highly used in displaying real-time data. Online gaming, Trading, streaming data, Sports update are some of the uses cases.