Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Note: This feature is available in Web Workers.
The WebSocketStream()
constructor creates a new WebSocketStream
object instance.
new WebSocketStream(url)
new WebSocketStream(url, options)
Parameters
url
A string representing the URL of the WebSocket server you want to connect to with this WebSocketStream
instance. Allowed URL schemes are "ws"
, "wss"
, "http"
, and "https"
.
options
Optional
An object that can contain the following properties:
protocols
Optional
A single string or an array of strings representing the sub-protocol(s) that the client would like to use, for example "amqp"
or "mqtt"
. Subprotocols may be selected from the IANA WebSocket Subprotocol Name Registry or may be custom names jointly understood by the client and the server. A single server can implement multiple WebSocket sub-protocols, and handle different types of interactions depending on the specified value. If it is omitted, an empty array is used by default. If protocols
is included, the connection will only be established if the server reports that it has selected one of these sub-protocols.
signal
Optional
An AbortSignal
belonging to an AbortController
that you want to use to close the WebSocket connection.
SyntaxError
DOMException
Thrown if the URL scheme is not one of "ws"
, "wss"
, "http"
, or "https"
.
The most basic example takes the URL of a WebSocket server as an argument:
const wss = new WebSocketStream("wss://example.com/wss");
A more advanced example could also include an options object containing custom protocols and/or an AbortSignal
:
const controller = new AbortController();
const queueWSS = new WebSocketStream("wss://example.com/queue", {
protocols: ["amqp", "mqtt"],
signal: controller.signal,
});
At a later time, AbortController.abort()
can be called when required to close the connection:
Alternatively, you can use the WebSocketStream.close()
method to close a connection, however this is mainly needed if you wish to specify a custom code and/or reason for the server to report.
See Using WebSocketStream to write a client for a complete example with full explanation.
SpecificationsNot currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.
Browser compatibility See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4