2021-07-12 06:44:49 -04:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
|
|
|
/// <reference no-default-lib="true" />
|
|
|
|
/// <reference lib="esnext" />
|
|
|
|
|
|
|
|
declare namespace Deno {
|
|
|
|
export interface WebSocketUpgrade {
|
|
|
|
response: Response;
|
2021-07-28 07:13:14 -04:00
|
|
|
socket: WebSocket;
|
2021-07-12 06:44:49 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export interface UpgradeWebSocketOptions {
|
|
|
|
protocol?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** **UNSTABLE**: new API, yet to be vetted.
|
|
|
|
*
|
|
|
|
* Used to upgrade an incoming HTTP request to a WebSocket.
|
|
|
|
*
|
|
|
|
* Given a request, returns a pair of WebSocket and Response. The original
|
|
|
|
* request must be responded to with the returned response for the websocket
|
|
|
|
* upgrade to be successful.
|
|
|
|
*
|
|
|
|
* ```ts
|
|
|
|
* const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
|
|
|
|
* const httpConn = Deno.serveHttp(conn);
|
|
|
|
* const e = await httpConn.nextRequest();
|
|
|
|
* if (e) {
|
2021-07-28 07:13:14 -04:00
|
|
|
* const { socket, response } = Deno.upgradeWebSocket(e.request);
|
|
|
|
* socket.onopen = () => {
|
|
|
|
* socket.send("Hello World!");
|
2021-07-12 06:44:49 -04:00
|
|
|
* };
|
2021-07-28 07:13:14 -04:00
|
|
|
* socket.onmessage = (e) => {
|
2021-07-12 06:44:49 -04:00
|
|
|
* console.log(e.data);
|
2021-07-28 07:13:14 -04:00
|
|
|
* socket.close();
|
2021-07-12 06:44:49 -04:00
|
|
|
* };
|
2021-07-28 07:13:14 -04:00
|
|
|
* socket.onclose = () => console.log("WebSocket has been closed.");
|
|
|
|
* socket.onerror = (e) => console.error("WebSocket error:", e.message);
|
2021-07-12 06:44:49 -04:00
|
|
|
* e.respondWith(response);
|
|
|
|
* }
|
|
|
|
* ```
|
|
|
|
*
|
|
|
|
* If the request body is disturbed (read from) before the upgrade is
|
|
|
|
* completed, upgrading fails.
|
|
|
|
*
|
|
|
|
* This operation does not yet consume the request or open the websocket. This
|
|
|
|
* only happens once the returned response has been passed to `respondWith`.
|
|
|
|
*/
|
|
|
|
export function upgradeWebSocket(
|
|
|
|
request: Request,
|
|
|
|
options?: UpgradeWebSocketOptions,
|
|
|
|
): WebSocketUpgrade;
|
|
|
|
}
|