summaryrefslogtreecommitdiff
path: root/std/examples/chat/server.ts
diff options
context:
space:
mode:
Diffstat (limited to 'std/examples/chat/server.ts')
-rw-r--r--std/examples/chat/server.ts65
1 files changed, 65 insertions, 0 deletions
diff --git a/std/examples/chat/server.ts b/std/examples/chat/server.ts
new file mode 100644
index 000000000..7a5a3ea14
--- /dev/null
+++ b/std/examples/chat/server.ts
@@ -0,0 +1,65 @@
+import { listenAndServe } from "../../http/server.ts";
+import {
+ acceptWebSocket,
+ acceptable,
+ WebSocket,
+ isWebSocketCloseEvent
+} from "../../ws/mod.ts";
+
+const clients = new Map<number, WebSocket>();
+let clientId = 0;
+async function dispatch(msg: string): Promise<void> {
+ for (const client of clients.values()) {
+ client.send(msg);
+ }
+}
+async function wsHandler(ws: WebSocket): Promise<void> {
+ const id = ++clientId;
+ clients.set(id, ws);
+ dispatch(`Connected: [${id}]`);
+ for await (const msg of ws.receive()) {
+ console.log(`msg:${id}`, msg);
+ if (typeof msg === "string") {
+ dispatch(`[${id}]: ${msg}`);
+ } else if (isWebSocketCloseEvent(msg)) {
+ clients.delete(id);
+ dispatch(`Closed: [${id}]`);
+ break;
+ }
+ }
+}
+
+listenAndServe({ port: 8080 }, async req => {
+ if (req.method === "GET" && req.url === "/") {
+ //Serve with hack
+ const u = new URL("./index.html", import.meta.url);
+ if (u.protocol.startsWith("http")) {
+ // server launched by deno run http(s)://.../server.ts,
+ fetch(u.href).then(resp => {
+ resp.headers.set("content-type", "text/html");
+ return req.respond(resp);
+ });
+ } else {
+ // server launched by deno run ./server.ts
+ const file = await Deno.open("./index.html");
+ req.respond({
+ status: 200,
+ headers: new Headers({
+ "content-type": "text/html"
+ }),
+ body: file
+ });
+ }
+ }
+ if (req.method === "GET" && req.url === "/ws") {
+ if (acceptable(req)) {
+ acceptWebSocket({
+ conn: req.conn,
+ bufReader: req.r,
+ bufWriter: req.w,
+ headers: req.headers
+ }).then(wsHandler);
+ }
+ }
+});
+console.log("chat server starting on :8080....");