WebSocket

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.

Constructor

WebSocket(url[, protocols])
Returns a newly created WebSocket object.

Constants

Constant Value
WebSocket.CONNECTING 0
WebSocket.OPEN 1
WebSocket.CLOSING 2
WebSocket.CLOSED 3

Properties

WebSocket.binaryType (en-US)
The binary data type used by the connection.
WebSocket.bufferedAmount (en-US) Read only
The number of bytes of queued data.
WebSocket.extensions (en-US) Read only
The extensions selected by the server.
WebSocket.onclose (en-US)
An event listener to be called when the connection is closed.
WebSocket.onerror (en-US)
An event listener to be called when an error occurs.
WebSocket.onmessage (en-US)
An event listener to be called when a message is received from the server.
WebSocket.onopen (en-US)
An event listener to be called when the connection is opened.
WebSocket.protocol (en-US) Read only
The sub-protocol selected by the server.
WebSocket.readyState (en-US) Read only
The current state of the connection.
WebSocket.url (en-US) Read only
The absolute URL of the WebSocket.

Methods

WebSocket.close([code[, reason]]) (en-US)
Closes the connection.
WebSocket.send(data) (en-US)
Enqueues data to be transmitted.

Events

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

close
Fired when a connection with a WebSocket is closed.
Also available via the onclose property
error
Fired when a connection with a WebSockethas been closed because of an error, such as when some data couldn't be sent.
Also available via the onerror property.
message
Fired when data is received through a WebSocket.
Also available via the onmessage property.
open
Fired when a connection with a WebSocketis opened.
Also available via the onopen property.

Examples

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

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

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

Specifications

Specification Status
HTML Living Standard
The definition of 'WebSocket' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also