WebSocket
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
Note: This feature is available inWeb Workers.
TheWebSocket object provides the API for creating and managing aWebSocket connection to a server, as well as for sending and receiving data on the connection.
To construct aWebSocket, use theWebSocket() constructor.
Note:TheWebSocket API has no way to applybackpressure, 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, seeWebSocketStream.
In this article
Constructor
WebSocket()Returns a newly created
WebSocketobject.
Instance properties
WebSocket.binaryTypeThe binary data type used by the connection.
WebSocket.bufferedAmountRead onlyThe number of bytes of queued data.
WebSocket.extensionsRead onlyThe extensions selected by the server.
WebSocket.protocolRead onlyThe sub-protocol selected by the server.
WebSocket.readyStateRead onlyThe current state of the connection.
WebSocket.urlRead onlyThe absolute URL of the WebSocket.
Instance methods
WebSocket.close()Closes the connection.
WebSocket.send()Enqueues data to be transmitted.
Events
Listen to these events usingaddEventListener() or by assigning an event listener to theoneventname property of this interface.
closeFired when a connection with a
WebSocketis closed.Also available via theonclosepropertyerrorFired 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.messageFired when data is received through a
WebSocket.Also available via theonmessageproperty.openFired when a connection with a
WebSocketis opened.Also available via theonopenproperty.
Examples
// Create WebSocket connection.const socket = new WebSocket("ws://localhost:8080");// Connection openedsocket.addEventListener("open", (event) => { socket.send("Hello Server!");});// Listen for messagessocket.addEventListener("message", (event) => { console.log("Message from server ", event.data);});Specifications
| Specification |
|---|
| WebSockets> # the-websocket-interface> |