2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-05-14 15:19:12 -04:00
|
|
|
import { serve } from "../http/server.ts";
|
|
|
|
import {
|
|
|
|
acceptWebSocket,
|
|
|
|
isWebSocketCloseEvent,
|
|
|
|
isWebSocketPingEvent,
|
2020-06-04 15:13:33 -04:00
|
|
|
WebSocket,
|
2019-05-14 15:19:12 -04:00
|
|
|
} from "./mod.ts";
|
|
|
|
|
2020-06-04 15:13:33 -04:00
|
|
|
async function handleWs(sock: WebSocket): Promise<void> {
|
|
|
|
console.log("socket connected!");
|
|
|
|
try {
|
|
|
|
for await (const ev of sock) {
|
|
|
|
if (typeof ev === "string") {
|
|
|
|
// text message
|
|
|
|
console.log("ws:Text", ev);
|
|
|
|
await sock.send(ev);
|
|
|
|
} else if (ev instanceof Uint8Array) {
|
|
|
|
// binary message
|
|
|
|
console.log("ws:Binary", ev);
|
|
|
|
} else if (isWebSocketPingEvent(ev)) {
|
|
|
|
const [, body] = ev;
|
|
|
|
// ping
|
|
|
|
console.log("ws:Ping", body);
|
|
|
|
} else if (isWebSocketCloseEvent(ev)) {
|
|
|
|
// close
|
|
|
|
const { code, reason } = ev;
|
|
|
|
console.log("ws:Close", code, reason);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.error(`failed to receive frame: ${err}`);
|
|
|
|
|
|
|
|
if (!sock.isClosed) {
|
|
|
|
await sock.close(1000).catch(console.error);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-09 08:34:47 -04:00
|
|
|
if (import.meta.main) {
|
|
|
|
/** websocket echo server */
|
|
|
|
const port = Deno.args[0] || "8080";
|
|
|
|
console.log(`websocket server is running on :${port}`);
|
|
|
|
for await (const req of serve(`:${port}`)) {
|
|
|
|
const { conn, r: bufReader, w: bufWriter, headers } = req;
|
2020-06-04 15:13:33 -04:00
|
|
|
acceptWebSocket({
|
|
|
|
conn,
|
|
|
|
bufReader,
|
|
|
|
bufWriter,
|
|
|
|
headers,
|
|
|
|
})
|
|
|
|
.then(handleWs)
|
|
|
|
.catch(async (e) => {
|
|
|
|
console.error(`failed to accept websocket: ${e}`);
|
|
|
|
await req.respond({ status: 400 });
|
2020-05-09 08:34:47 -04:00
|
|
|
});
|
2020-05-04 12:27:06 -04:00
|
|
|
}
|
2019-05-14 15:19:12 -04:00
|
|
|
}
|