Table of contents
  1. WebSockets
    1. Creating a WebSocket Connection
    2. WebSocket Events
    3. Sending Data
    4. Closing the Connection




WebSockets

WebSockets use a protocol that starts with ws:/ / (unencrypted) or wss:// (encrypted) instead of http:// or https://

Creating a WebSocket Connection

To establish a WebSocket connection in JavaScript, create a new WebSocket object, passing the WebSocket server URL as a parameter.

const socket = new WebSocket('ws://example.com/socket');

WebSocket Events

WebSocket objects emit various events to handle different stages of the connection.

  • open : Triggered when the connection is successfully established
socket.addEventListener('open', (event) => {
// Connection is open. 
});

socket.addEventListener('message', (event) => {
    const message = event.data;
// Handle incoming message. 
});
  • error: Triggered when an error occurs
socket.addEventListener('error', (event) => { console.error('WebSocket error:', event); });
  • close: Fired when the connection is closed
socket.addEventListener('close', (event) => {
    if (event.wasClean) {
        console.log('Connection closed cleanly, code=${event.code), reason=$(event.reason}');
    }
    else {
        console.error('Connection abruptly closed');
    }
});

Sending Data

To send data to the server, use the send method of the WebSocket object. Data can be a string, Array Buffer, or Blob.

socket.send('Hello, server!');

Closing the Connection

To close the WebSocket connection, call the close method on the WebSocket object.

socket.close();