Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 11 additions & 22 deletions files/en-us/web/api/websockets_api/using_websocketstream/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ To create a WebSocket client, you first need to create a new `WebSocketStream` i
const wss = new WebSocketStream("wss://example.com/wss");
```

It can also take an options object containing custom protocols and/or an {{domxref("AbortSignal")}} (see [Closing the connection](#closing_the_connection)):
It can also take an `options` object containing custom protocols and/or an {{domxref("AbortSignal")}}. The `AbortSignal` can be used to abort the connection attempt before the [handshake](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#the_websocket_handshake) has completed (that is, before the {{domxref("WebSocketStream.opened", "opened")}} promise resolves). It is typically used to implement a connection timeout. For example, the following code will time out if the handshake takes more than 5 seconds to complete:

```js
const controller = new AbortController();
const queueWSS = new WebSocketStream("wss://example.com/queue", {
protocols: ["amqp", "mqtt"],
signal: controller.signal,
signal: AbortSignal.timeout(5000),
});
```

Expand Down Expand Up @@ -76,26 +76,7 @@ The browser automatically controls the rate at which the client receives and sen

## Closing the connection

With `WebSocketStream`, the information previously available via the `WebSocket` {{domxref("WebSocket.close_event", "close")}} and {{domxref("WebSocket.error_event", "error")}} events is now available via the {{domxref("WebSocketStream.closed", "closed")}} property — this returns a promise that fulfills with an object containing the closing code (see the full list of [`CloseEvent` status codes](/en-US/docs/Web/API/CloseEvent/code#value)) and reason indicating why the server closed the connection:

```js
const { code, reason } = await wss.closed;
```

As mentioned earlier, the WebSocket connection can be closed using an {{domxref("AbortController")}}. The necessary {{domxref("AbortSignal")}} is passed to the `WebSocketStream` constructor during creation, and {{domxref("AbortController.abort()")}} can then be called when required:

```js
const controller = new AbortController();
const wss = new WebSocketStream("wss://example.com/wss", {
signal: controller.signal,
});

// some time later

controller.abort();
```

Alternatively you can use the {{domxref("WebSocketStream.close()")}} method to close a connection. This is mainly used if you wish to specify a custom code and/or reason:
To close a connection, call the {{domxref("WebSocketStream.close()")}} method, optionally passing a [closing code](/en-US/docs/Web/API/CloseEvent/code#value) and reason:

```js
wss.close({
Expand All @@ -107,6 +88,14 @@ wss.close({
> [!NOTE]
> Depending on the server setup and status code you use, the server may choose to ignore a custom code in favor of a valid code that is correct for the closing reason.

Closing the underlying {{domxref("WritableStream")}} or {{domxref("WritableStreamDefaultWriter")}} also closes the connection.

To handle connection closure, wait for the {{domxref("WebSocketStream.closed", "closed")}} promise to resolve:

```js
const { closeCode, reason } = await wss.closed;
```

## A complete sample client

To demonstrate basic usage of `WebSocketStream`, we've created a sample client. You can see the [full listing](#full_listing) at the bottom of the article, and follow along with the explanation below.
Expand Down
2 changes: 0 additions & 2 deletions files/en-us/web/api/websocketstream/close/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ browser-compat: api.WebSocketStream.close
The **`close()`** method of the
{{domxref("WebSocketStream")}} interface closes the WebSocket connection. The method optionally accepts an object containing a custom code and/or reason indicating why the connection was closed.

An alternative mechanism for closing a `WebSocketStream` is to specify an {{domxref("AbortSignal")}} in the [`signal`](/en-US/docs/Web/API/WebSocketStream/WebSocketStream#signal) option of the constructor upon creation. The associated {{domxref("AbortController")}} can then be used to close the WebSocket connection. This is generally the preferred mechanism. However, `close()` can be used if you wish to specify a custom code and/or reason.

## Syntax

```js-nolint
Expand Down
17 changes: 8 additions & 9 deletions files/en-us/web/api/websocketstream/websocketstream/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,44 +31,43 @@ new WebSocketStream(url, options)
- `signal` {{optional_inline}}
- : An {{domxref("AbortSignal")}}, which can be used to abort the connection before the [handshake](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#the_websocket_handshake) has completed (that is, before the {{domxref("WebSocketStream.opened", "opened")}} promise resolves). This is primarily intended to help implement connection timeouts. As such, it does nothing after the connection is established.


### Exceptions

- `SyntaxError` {{domxref("DOMException")}}
- : Thrown if the URL scheme is not one of `"ws"`, `"wss"`, `"http"`, or `"https"`.

## Examples

### Creating a `WebSocketStream`

The most basic example takes the URL of a WebSocket server as an argument:

```js
const wss = new WebSocketStream("wss://example.com/wss");
```

A more advanced example could also include an options object containing custom protocols and/or an {{domxref("AbortSignal")}}. The following example will time out if the connection is not established within 5 seconds:
### Creating a `WebSocketStream` with a connection timeout

The following example uses the `signal` option to implement a timeout if the connection is not established within 5 seconds:

```js
const queueWSS = new WebSocketStream("wss://example.com/queue", {
protocols: ["amqp", "mqtt"],
signal: AbortSignal.timeout(5000),
});
```

If you're connecting to localhost, it's likely to succeed or fail almost instantly, so this will have no effect.
Note that if you're connecting to localhost, it's likely to succeed or fail before the connection attempt times out.

You can use the {{domxref("WebSocketStream.close()")}} method to close a connection.

`WritableStream.close()` and `WritableStreamDefaultWriter.close()` from the `writable` of the fulfilled `opened` `Promise` also closes the connection.
Once the connection is established, `signal` has no effect: to close a connection that's already established, call the {{domxref("WebSocketStream.close()")}} method. Closing the underlying {{domxref("WritableStream")}} or {{domxref("WritableStreamDefaultWriter")}} also closes the socket.

See [Using WebSocketStream to write a client](/en-US/docs/Web/API/WebSockets_API/Using_WebSocketStream) for a complete example with full explanation.

## Specifications

Not currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.
Not currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.

[WebSocketStream API design](https://docs.google.com/document/d/1La1ehXw76HP6n1uUeks-WJGFgAnpX2tCjKts7QFJ57Y/edit?pli=1&tab=t.0).


## Browser compatibility

{{Compat}}
Expand Down