Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Editorial review: Document WebSocketStream#35548

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
wbamberg merged 19 commits intomdn:mainfromchrisdavidmills:websocketstream
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from1 commit
Commits
Show all changes
19 commits
Select commitHold shift + click to select a range
0440e77
Document WebSocketStream
chrisdavidmillsAug 22, 2024
fb8a621
Add WebSocket interface documentation
chrisdavidmillsAug 23, 2024
54ab5af
Merge branch 'main' into websocketstream
chrisdavidmillsAug 23, 2024
3c8f355
Update files/en-us/web/api/websockets_api/using_websocketstream/index.md
chrisdavidmillsAug 28, 2024
6ca71c9
Update files/en-us/web/api/websockets_api/using_websocketstream/index.md
chrisdavidmillsAug 28, 2024
7a55d73
Update files/en-us/web/api/websockets_api/using_websocketstream/index.md
chrisdavidmillsAug 28, 2024
8f60ee6
Update files/en-us/web/api/websockets_api/using_websocketstream/index.md
chrisdavidmillsAug 28, 2024
a979ad4
Update files/en-us/web/api/websockets_api/using_websocketstream/index.md
chrisdavidmillsAug 28, 2024
1016e40
Update files/en-us/web/api/websockets_api/using_websocketstream/index.md
chrisdavidmillsAug 28, 2024
f2e04e4
Update files/en-us/web/api/websocketstream/closed/index.md
chrisdavidmillsAug 28, 2024
2c01603
Update files/en-us/web/api/websocketstream/opened/index.md
chrisdavidmillsAug 28, 2024
76923cc
Update files/en-us/web/api/websocketstream/url/index.md
chrisdavidmillsAug 28, 2024
71defc9
Update files/en-us/web/api/websocketstream/websocketstream/index.md
chrisdavidmillsAug 28, 2024
2a82373
make protocol usage consistent ascross example snippets
chrisdavidmillsAug 28, 2024
190b3da
Merge branch 'main' into websocketstream
chrisdavidmillsSep 6, 2024
bbb9b37
Fixes for wbamberg review comments
chrisdavidmillsSep 6, 2024
f72d08d
Merge branch 'main' into websocketstream
chrisdavidmillsSep 6, 2024
2c2ceed
Fixes for 2nd round of wbamberg review
chrisdavidmillsSep 9, 2024
7bc83c3
typo
wbambergSep 12, 2024
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
PrevPrevious commit
NextNext commit
Fixes for 2nd round of wbamberg review
  • Loading branch information
@chrisdavidmills
chrisdavidmills committedSep 9, 2024
commit2c2ceedd6a26517ec4ed4e694e9e773876878d53
4 changes: 2 additions & 2 deletionsfiles/en-us/web/api/closeevent/code/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,11 +8,11 @@ browser-compat: api.CloseEvent.code

{{APIRef("Websockets API")}}

The **`code`** read-only property of the {{domxref("CloseEvent")}} interface returns a [WebSocket connection close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5) indicating the reason theserver gave for closing the connection.
The **`code`** read-only property of the {{domxref("CloseEvent")}} interface returns a [WebSocket connection close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5) indicating the reason theconnection was closed.

## Value

An integer [WebSocket connection close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5) in the range `1000` - `4999`, indicating the reason theserver gave for closing the connection.
An integer [WebSocket connection close code](https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5) in the range `1000` - `4999`, indicating the reason theconnection was closed.

<table class="no-markdown">
<thead>
Expand Down
2 changes: 1 addition & 1 deletionfiles/en-us/web/api/closeevent/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ A `CloseEvent` is sent to clients using {{Glossary("WebSockets")}} when the conn
_This interface also inherits properties from its parent, {{domxref("Event")}}._

- {{domxref("CloseEvent.code")}} {{ReadOnlyInline}}
- : Returns an `unsigned short` containing the close code sent by the server.
- : Returns an `unsigned short` containing the close code.
- {{domxref("CloseEvent.reason")}} {{ReadOnlyInline}}
- : Returns a string indicating the reason the server closed the connection. This is specific to the particular server and sub-protocol.
- {{domxref("CloseEvent.wasClean")}} {{ReadOnlyInline}}
Expand Down
2 changes: 1 addition & 1 deletionfiles/en-us/web/api/websockets_api/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,7 @@ browser-compat:

{{DefaultAPISidebar("WebSockets API")}}

The **WebSocket API**is an advanced technology thatmakes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.
The **WebSocket API** makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive responses without having to poll the server for a reply.

The WebSocket API provides two alternative mechanisms for creating and using web socket connections: the {{domxref("WebSocket")}} interface and the {{domxref("WebSocketStream")}} interface.

Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,7 +9,7 @@ status:

{{DefaultAPISidebar("WebSockets API")}}{{non-standard_header}}

The {{domxref("WebSocketStream")}} API is a {{jsxref("Promise")}}-based alternative to {{domxref("WebSocket")}} for creating and using client-side WebSocket connections. `WebSocketStream` uses the [Streams API](/en-US/docs/Web/API/Streams_API) to handle receiving and sending messages, meaning that socket connections can take advantage of stream [backpressure](/en-US/docs/Web/API/Streams_API/Concepts#backpressure) automatically, regulating the speed of reading or writing to avoid bottlenecks in the application.
The {{domxref("WebSocketStream")}} API is a {{jsxref("Promise")}}-based alternative to {{domxref("WebSocket")}} for creating and using client-side WebSocket connections. `WebSocketStream` uses the [Streams API](/en-US/docs/Web/API/Streams_API) to handle receiving and sending messages, meaning that socket connections can take advantage of stream [backpressure](/en-US/docs/Web/API/Streams_API/Concepts#backpressure) automatically (no additional action required by the developer), regulating the speed of reading or writing to avoid bottlenecks in the application.

This article explains how to use the {{domxref("WebSocketStream")}} API to create a WebSocket client.

Expand DownExpand Up@@ -75,9 +75,11 @@ while (true) {
}
```

The browser automatically controls the rate at which the client receives and sends data by applying backpressure when needed. If data is arriving faster than the client can `read()` it, the underlying Streams API exerts backpressure on the server. In addition, `write()` operations will only proceed if it is safe to do so.

## 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 reasonsent by the server:
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 reasonindicating why the server closed the connection:

```js
const { code, reason } = await wss.closed;
Expand All@@ -96,7 +98,7 @@ const wss = new WebSocketStream("wss://example.com/wss", {
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 reason for the server to report:
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:

```js
wss.close({
Expand All@@ -115,7 +117,7 @@ To demonstrate basic usage of `WebSocketStream`, we've created a sample client.
> [!NOTE]
> To get the example working, you'll also need a server component. We wrote our client to work along with the Deno server explained in [Writing a WebSocket server in JavaScript (Deno)](/en-US/docs/Web/API/WebSockets_API/Writing_a_WebSocket_server_in_JavaScript_Deno), but any compatible server will do.

The HTML for the demo is as follows. It includes informational{{htmlelment("h1")}} and {{htmlelment("h1")}} elements, a {{htmlelment("button")}} to close the WebSocket connection that is initially disabled, and a {{htmlelment("div")}} for us to write output messages into.
The HTML for the demo is as follows. It includes informational[`<h2>`](/en-US/docs/Web/HTML/Element/Heading_Elements) and {{htmlelement("p")}} elements, a {{htmlelement("button")}} to close the WebSocket connection that is initially disabled, and a {{htmlelement("div")}} for us to write output messages into.

```html
<h2>WebSocketStream Test</h2>
Expand All@@ -131,7 +133,9 @@ const output = document.querySelector("#output");
const closeBtn = document.querySelector("#close");

function writeToScreen(message) {
output.insertAdjacentHTML("beforeend", `<p>${message}</p>`);
const pElem = document.createElement("p");
pElem.textContent = message;
output.appendChild(pElem);
}
```

Expand DownExpand Up@@ -167,7 +171,7 @@ async function start() {
const reader = readable.getReader();
const writer = writable.getWriter();

awaitwriter.write("ping");
writer.write("ping");
writeToScreen("SENT: ping");

while (true) {
Expand All@@ -178,15 +182,22 @@ async function start() {
}

setTimeout(async () => {
await writer.write("ping");
writeToScreen("SENT: ping");
try {
await writer.write("ping");
writeToScreen("SENT: ping");
} catch (e) {
writeToScreen(`Error writing to socket: ${e.message}`);
}
}, 5000);
}
}

start();
```

> [!NOTE]
> The {{domxref("setTimeout")}} function wraps the `write()` call in a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block to handle any errors that can arise if the application tries to write to the stream after it has been closed.

We now include a promise-style code section to inform the user of the code and reason if the WebSocket connection is closed, as signalled by the {{domxref("WebSocketStream.closed", "closed")}} promise fulfilling:

```js
Expand All@@ -207,7 +218,7 @@ closeBtn.addEventListener("click", () => {
reason: "That's all folks",
});

closeBtn.disabled =false;
closeBtn.disabled =true;
});
```

Expand All@@ -231,7 +242,9 @@ closeBtn.addEventListener("click", () => {
const closeBtn = document.querySelector("#close");

function writeToScreen(message) {
output.insertAdjacentHTML("beforeend", `<p>${message}</p>`);
const pElem = document.createElement("p");
pElem.textContent = message;
output.appendChild(pElem);
}

if (!("WebSocketStream" in self)) {
Expand All@@ -249,7 +262,7 @@ closeBtn.addEventListener("click", () => {
const reader = readable.getReader();
const writer = writable.getWriter();

awaitwriter.write("ping");
writer.write("ping");
writeToScreen("SENT: ping");

while (true) {
Expand All@@ -259,8 +272,8 @@ closeBtn.addEventListener("click", () => {
break;
}

setTimeout(async() => {
awaitwriter.write("ping");
setTimeout(() => {
writer.write("ping");
writeToScreen("SENT: ping");
}, 5000);
}
Expand All@@ -281,7 +294,7 @@ closeBtn.addEventListener("click", () => {
reason: "That's all folks",
});

closeBtn.disabled =false;
closeBtn.disabled =true;
});
}
</script>
Expand Down
6 changes: 3 additions & 3 deletionsfiles/en-us/web/api/websocketstream/close/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,9 @@ browser-compat: api.WebSocketStream.close
{{APIRef("WebSockets API")}}{{non-standard_header}}

The **`close()`** method of the
{{domxref("WebSocketStream")}} interface closes the WebSocket connection. The method optionally accepts an objectspecifying a custom code and reasonfortheserver to report.
{{domxref("WebSocketStream")}} interface closes the WebSocket connection. The method optionally accepts an objectcontaining a custom code and/or reasonindicating whytheconnection 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 reason for the server to report.
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

Expand All@@ -28,7 +28,7 @@ close(options)
- `options` {{optional_inline}}
- : An options object containing the following properties:
- `closeCode` {{optional_inline}}
- : A number representing the closing codesent by the server(see the full list of [`CloseEvent` status codes](/en-US/docs/Web/API/CloseEvent/code#value)).
- : A number representing the closing code (see the full list of [`CloseEvent` status codes](/en-US/docs/Web/API/CloseEvent/code#value)).
- `reason` {{optional_inline}}
- : A string representing a human-readable description of the reason why the socket connection is closed. The maximum allowed length for a `reason` string is 123 bytes. The string is automatically encoded as UTF-8 when the function is invoked.

Expand Down
6 changes: 3 additions & 3 deletionsfiles/en-us/web/api/websocketstream/closed/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,16 +12,16 @@ browser-compat: api.WebSocketStream.closed
{{APIRef("WebSockets API")}}{{non-standard_header}}

The **`closed`** read-only property of the
{{domxref("WebSocketStream")}} interface returns a {{jsxref("Promise")}} that fulfills with an object once the socket connection is closed. The object contains the closing code and reason, as sent by the server.
{{domxref("WebSocketStream")}} interface returns a {{jsxref("Promise")}} that fulfills with an object once the socket connection is closed. The object contains the closing code and reason.

## Value

A promise, which fulfills with an object containing the following properties:

- `closeCode`
- : A number representing the closing codesent by the server(see the full list of [`CloseEvent` status codes](/en-US/docs/Web/API/CloseEvent/code#value)).
- : A number representing the closing code (see the full list of [`CloseEvent` status codes](/en-US/docs/Web/API/CloseEvent/code#value)).
- `reason`
- : A string representing a human-readable description of the reason why the socket connectionis closed.
- : A string representing a human-readable description of the reason why the socket connectionwas closed.

The promise rejects if the WebSocket connection did not close cleanly (for a clean close, the associated TCP connection must be closed _after_ the WebSocket closing handshake is completed).

Expand Down
21 changes: 12 additions & 9 deletionsfiles/en-us/web/api/websocketstream/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,22 +39,27 @@ The **`WebSocketStream`** interface of the {{domxref("WebSockets API", "WebSocke
const output = document.querySelector("#output");

function writeToScreen(message) {
output.insertAdjacentHTML("beforeend", `<p>${message}</p>`);
const pElem = document.createElement("p");
pElem.textContent = message;
output.appendChild(pElem);
}

if ("WebSocketStream" in self) {
const wsURL = "wss://127.0.0.1/";
if (!("WebSocketStream" in self)) {
writeToScreen("Your browser does not support WebSocketStream");
} else {
const wsURL = "ws://127.0.0.1/";
const wss = new WebSocketStream(wsURL);

console.log(wss.url);

async function start() {
const { readable, writable } = await wss.opened;
const { readable, writable, extensions, protocol } = await wss.opened;
writeToScreen("CONNECTED");
closeBtn.disabled = false;
const reader = readable.getReader();
const writer = writable.getWriter();

awaitwriter.write("ping");
writer.write("ping");
writeToScreen("SENT: ping");

while (true) {
Expand All@@ -64,16 +69,14 @@ if ("WebSocketStream" in self) {
break;
}

setTimeout(async() => {
awaitwriter.write("ping");
setTimeout(() => {
writer.write("ping");
writeToScreen("SENT: ping");
}, 5000);
}
}

start();
} else {
writeToScreen("Your browser does not support WebSocketStream");
}
```

Expand Down
8 changes: 4 additions & 4 deletionsfiles/en-us/web/api/websocketstream/opened/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ A promise, which fulfills with an object containing the following properties:
- `extensions`
- : A string representing any extensions applied to the `WebSocketStream`. Such extensions are not currently defined, but may be in the future. Currently returns an empty string.
- `protocol`
- : A string representingany customprotocol used to open the current WebSocket connection, asspecified in the [`protocols`](/en-US/docs/Web/API/WebSocketStream/WebSocketStream#protocols) option of the `WebSocketStream()` constructor. Returns an empty string if nocustomprotocolwas set during instantiation.
- : A string representingthe sub-protocol used to open the current WebSocket connection (chosen from the optionsspecified in the [`protocols`](/en-US/docs/Web/API/WebSocketStream/WebSocketStream#protocols) option of the `WebSocketStream()` constructor). Returns an empty string if nosub-protocol has been used to open the connection (i.e. no sub-protocoloptions were included in the constructor call).
- `readable`
- : A {{domxref("ReadableStream")}} instance. Call {{domxref("ReadableStream.getReader()")}} on it to obtain a {{domxref("ReadableStreamDefaultReader")}} instance that can be used to read incoming WebSocket data.
- `writable`
Expand All@@ -41,16 +41,16 @@ async function start() {
const reader = readable.getReader();
const writer = writable.getWriter();

awaitwriter.write("ping");
writer.write("ping");

while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}

setTimeout(async() => {
awaitwriter.write("ping");
setTimeout(() => {
writer.write("ping");
}, 5000);
}
}
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,7 +28,7 @@ new WebSocketStream(url, options)
- `options` {{optional_inline}}
- : An object that can contain the following properties:
- `protocols` {{optional_inline}}
- : A single string or an array of strings representing the sub-protocol(s) that the client would like to use, for example `"chat"` or `"chatv2"`. Subprotocols may be selected from the [IANA WebSocket Subprotocol Name Registry](https://www.iana.org/assignments/websocket/websocket.xml#subprotocol-name) 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.
- : A single string or an array of strings representing the sub-protocol(s) that the client would like to use, for example `"chat"` or `"chatv2"`. Subprotocols may be selected from the [IANA WebSocket Subprotocol Name Registry](https://www.iana.org/assignments/websocket/websocket.xml#subprotocol-name) 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_inline}}
- : An {{domxref("AbortSignal")}} belonging to an {{domxref("AbortController")}} that you want to use to close the WebSocket connection.

Expand DownExpand Up@@ -61,7 +61,7 @@ At a later time, {{domxref("AbortController.abort()")}} can be called when requi
controller.abort();
```

Alternatively, you can use the {{domxref("WebSocketStream.close()")}} method to close a connection, however this is mainly needed if you wish to specify a custom code and reason for the server to report.
Alternatively, you can use the {{domxref("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](/en-US/docs/Web/API/WebSockets_API/Using_WebSocketStream) for a complete example with full explanation.

Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp