2020-02-22 18:51:04 -05:00
|
|
|
import { listenAndServe } from "../../http/server.ts";
|
|
|
|
import {
|
|
|
|
acceptWebSocket,
|
|
|
|
acceptable,
|
|
|
|
WebSocket,
|
|
|
|
isWebSocketCloseEvent
|
|
|
|
} from "../../ws/mod.ts";
|
|
|
|
|
|
|
|
const clients = new Map<number, WebSocket>();
|
|
|
|
let clientId = 0;
|
2020-03-20 09:38:34 -04:00
|
|
|
function dispatch(msg: string): void {
|
2020-02-22 18:51:04 -05:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-21 09:53:47 -04:00
|
|
|
const addr = Deno.args[0] ?? "127.0.0.1:8080";
|
|
|
|
|
|
|
|
listenAndServe(addr, async req => {
|
2020-02-22 18:51:04 -05:00
|
|
|
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 => {
|
2020-02-24 08:10:00 -05:00
|
|
|
return req.respond({
|
|
|
|
status: resp.status,
|
|
|
|
headers: new Headers({
|
|
|
|
"content-type": "text/html"
|
|
|
|
}),
|
|
|
|
body: resp.body
|
|
|
|
});
|
2020-02-22 18:51:04 -05:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
// server launched by deno run ./server.ts
|
2020-02-24 08:10:00 -05:00
|
|
|
const file = await Deno.open(u.pathname);
|
2020-02-22 18:51:04 -05:00
|
|
|
req.respond({
|
|
|
|
status: 200,
|
|
|
|
headers: new Headers({
|
|
|
|
"content-type": "text/html"
|
|
|
|
}),
|
|
|
|
body: file
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2020-02-24 08:10:00 -05:00
|
|
|
if (req.method === "GET" && req.url === "/favicon.ico") {
|
|
|
|
req.respond({
|
|
|
|
status: 302,
|
|
|
|
headers: new Headers({
|
|
|
|
location: "https://deno.land/favicon.ico"
|
|
|
|
})
|
|
|
|
});
|
|
|
|
}
|
2020-02-22 18:51:04 -05:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2020-03-21 09:53:47 -04:00
|
|
|
console.log(`chat server starting on ${addr}....`);
|