GeezerVison is showing developer.mozilla.org — WebSocketStream - Web APIs | MDN
WebSocketStream
Non-standard: This feature is not standardized. We do not recommend using non-standard features in production, as they have limited browser support, and may change or be removed. However, they can be a suitable alternative in specific cases where no standard option exists.
The WebSocketStream interface of the WebSockets API is a promise-based API for connecting to a WebSocket server. It uses streams to send and receive data on the connection, and can therefore take advantage of stream backpressure automatically, regulating the speed of reading or writing to avoid bottlenecks in the application.
url Read only
-
Returns the URL of the WebSocket server that the WebSocketStream instance was created with.
closed Read only
-
Returns a 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.
opened Read only
-
Returns a Promise that fulfills with an object once the socket connection is successfully opened. Among other features, this object contains a ReadableStream and a WritableStream instance for receiving and sending data on the connection.
close()
-
Closes the WebSocket connection.
js
const output = document.querySelector("#output");
function writeToScreen(message) {
const pElem = document.createElement("p");
pElem.textContent = message;
output.appendChild(pElem);
}
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, extensions, protocol } = await wss.opened;
writeToScreen("CONNECTED");
closeBtn.disabled = false;
const reader = readable.getReader();
const writer = writable.getWriter();
writer.write("ping");
writeToScreen("SENT: ping");
while (true) {
const { value, done } = await reader.read();
writeToScreen(`RECEIVED: ${value}`);
if (done) {
break;
}
setTimeout(() => {
writer.write("ping");
writeToScreen("SENT: ping");
}, 5000);
}
}
start();
}
See Using WebSocketStream to write a client for a complete example with full explanation.