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.
Note: This feature is available in Web Workers
Constructor
WebSocket()-
Returns a newly created
WebSocketobject.
Properties
WebSocket.binaryType-
The binary data type used by the connection.
WebSocket.bufferedAmountRead only-
The number of bytes of queued data.
WebSocket.extensionsRead only-
The extensions selected by the server.
WebSocket.protocolRead only-
The sub-protocol selected by the server.
WebSocket.readyStateRead only-
The current state of the connection.
WebSocket.urlRead only-
The absolute URL of the WebSocket.
Methods
WebSocket.close()-
Closes the connection.
WebSocket.send()-
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
WebSocketis closed. Also available via theoncloseproperty 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 theonerrorproperty. message-
Fired when data is received through a
WebSocket. Also available via theonmessageproperty. open-
Fired when a connection with a
WebSocketis opened. Also available via theonopenproperty.
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 |
|---|
| HTML Standard # the-websocket-interface |
Browser compatibility
BCD tables only load in the browser