docs.rodeo

MDN Web Docs mirror

WebSocket

{{APIRef("WebSockets API")}} {{AvailableInWorkers}} 

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

To construct a WebSocket, use the WebSocket() constructor.

[!NOTE] The WebSocket API has no way to apply backpressure, therefore when messages arrive faster than the application can process them, the application will either fill up the device’s memory by buffering those messages, become unresponsive due to 100% CPU usage, or both. For an alternative that provides backpressure automatically, see {{domxref("WebSocketStream")}} .

{{InheritanceDiagram}} 

Constructor

Instance properties

Instance methods

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

Examples

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

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

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

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN