DEV Community

Ayako yk
Ayako yk

Posted on

Understanding WebSocket in JavaScript

In a past blog post, I discussed using the fetch API to send requests to a server --- specifically, making HTTP requests to GET, POST, update data with PUT, or DELETE data. These are one-time, on-demand requests, which are particularly useful for working with static data.

However, when we need more frequent or continuous communication with a server, such as for a chat application or an online game, we can use a different approach: WebSocket.

The WebSocket API enables a two-way interactive communication session between a client and a server without the need for polling (constantly checking if new data is available).

There are several WebSocket API mechanisms:

WebSocket Interface
The WebSocket interface is stable, widely supported across browsers and servers, and easy to set up. Its main disadvantage is that it doesn't support backpressure (messages can arrive faster than the application can process, potentially leading to CPU overusage). However, for most simple, real-time applications, such as chat apps, this is usually not a problem.

WebSocketStream Interface
The WebSocketStream interface is a Promise-based and handles backpressure. However, it is not standardized and is only supported by one rendering engine.

WebTransport API
The WebTransport API is a newer, versatile low-level API and provides features that are not available in the WebSocket and WebSocketStream Interfaces. It is designed for more complex applications, such as video conferencing apps or online games. However, it is more complex to use and not widely supported.

Here, I'll take a closer look at WebSocket.

Constructor:

new WebSocket(url)
Enter fullscreen mode Exit fullscreen mode

The WebSocket constructor creates a WebSocket object and immediately attempts to establish a connection to the specified WebSocket URL.
The URL must use one of the following protocols: ws, wss, http, or https.
ws: WebSocket (non-encrypted)
wss: Secure WebSocket (encrypted, similar to HTTPS)

Image of TCP Connection

Image description
Source: Wikipedia

Events
open:
The open event is fired when a WenSocket connection is successfully established. The onopen property is also available.

Example:

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

// Connection opened
socket.addEventListener("open", (event) => {
  socket.send("Hello Server!");
});
Enter fullscreen mode Exit fullscreen mode

MDN

message:
The message event is fired when data is received through a WebSocket connection. The onmessage property is also available.

Example:

// Listen for messages
socket.addEventListener("message", (event) => {
  console.log("Message from server ", event.data);
});
Enter fullscreen mode Exit fullscreen mode

MDN

The data is read-only and can be either a string or a binary type (ArrayBuffer or Blob).

error:
The error event is fired when a WebSocket connection is closed due to an error. The onerror property is also available.

Example:

// Listen for possible errors
socket.addEventListener("error", (event) => {
  console.log("WebSocket error: ", event);
});
Enter fullscreen mode Exit fullscreen mode

MDN

close:
The close event is fired when a WebSocket connection is closed. The onclose property is also available.

Example:

socket.addEventListener("close", (event) => {
  console.log("The connection has been closed successfully.");
});
Enter fullscreen mode Exit fullscreen mode

(The example has been modified for consistency.)
MDN

CloseEvent:
code property
The code property provides a numeric code indicating the reason for the WebSocket connection's closure.
1000 - Normal closure (default)
1001 - The endpoint is going away (e.g., server shutting down)
etc.
For a complete list of close codes, refer to MDN.

reason property
The reason property provides a human-readable string indicating the reason for closing the connection.

wasClean property
The wasClean property returns a boolean value: true if the connection was closed cleanly; false otherwise.

send() Method
The send() method is used to send data to a server through a WebSocket connection.

Example:

socket.send(data)
Enter fullscreen mode Exit fullscreen mode

The data can be either a string or binary data (ArrayBuffer or Blob).

Rate Limiting
When sending a large amount of data over a slow internet connection, the send() method can be called multiple times. However, the data will be buffered (stored) in memory. This can be monitored using the bufferedAmount property.

Example:

// every 100ms examine the socket and send more data 
// only if all the existing data was sent out 
setInterval(() => { 
    if (socket.bufferedAmount == 0) { 
        socket.send(moreData()); 
    } 
}, 100);
Enter fullscreen mode Exit fullscreen mode

The Modern JavaScript Tutorial

WebSocket is a modern method for maintaining continuous communication with a server, without the limitations of cross-origin restrictions, and is widely supported by browsers. This opens up many possibilities for creating a variety of applications.

Top comments (0)