2 min read

WebSockets in JavaScript

The WebSocket API makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

1. Creating a Connection

To open a WebSocket connection, you simply create a new WebSocket object, passing the URL of the server.

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

2. Handling Events

The WebSocket object provides four main events to handle the connection lifecycle and incoming data.

Connection Opened (open)

Fired when the connection is successfully established.

socket.addEventListener('open', (event) => {
    socket.send('Hello Server!');
});

Message Received (message)

Fired when data is received from the server.

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

Error Occurred (error)

Fired when an error occurs.

socket.addEventListener('error', (event) => {
    console.error('WebSocket error:', event);
});

Connection Closed (close)

Fired when the connection is closed.

socket.addEventListener('close', (event) => {
    console.log('The connection has been closed successfully.');
});

3. Sending Data

You can send data using the send() method. It supports strings, Blobs, and ArrayBuffers.

socket.send("Hello");
socket.send(JSON.stringify({ type: "greeting", content: "Hello" }));

4. Closing the Connection

To close the connection, use the close() method.

socket.close();

5. WebSockets vs. HTTP

Feature HTTP WebSocket
Communication Half-duplex (Request-Response) Full-duplex (Bidirectional)
Initiator Client only Client or Server
Overhead High (Headers sent every time) Low (Initial handshake, then lightweight frames)
Use Case Fetching resources, REST APIs Real-time chat, gaming, live feeds

programming/javascript/vanilla/javascript programming/javascript/vanilla/ajax-fetch