2019-01-06 14:26:18 -05:00
|
|
|
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
|
2019-03-06 10:24:53 -05:00
|
|
|
import { serve } from "https://deno.land/std/http/mod.ts";
|
2019-01-06 14:26:18 -05:00
|
|
|
import {
|
|
|
|
acceptWebSocket,
|
|
|
|
isWebSocketCloseEvent,
|
|
|
|
isWebSocketPingEvent
|
2019-03-06 10:24:53 -05:00
|
|
|
} from "https://deno.land/std/ws/mod.ts";
|
2019-01-06 14:26:18 -05:00
|
|
|
|
2019-03-04 19:53:35 -05:00
|
|
|
async function main(): Promise<void> {
|
2019-01-06 14:26:18 -05:00
|
|
|
console.log("websocket server is running on 0.0.0.0:8080");
|
|
|
|
for await (const req of serve("0.0.0.0:8080")) {
|
|
|
|
if (req.url === "/ws") {
|
2019-04-24 07:41:23 -04:00
|
|
|
(async (): Promise<void> => {
|
2019-01-06 14:26:18 -05:00
|
|
|
const sock = await acceptWebSocket(req);
|
|
|
|
console.log("socket connected!");
|
|
|
|
for await (const ev of sock.receive()) {
|
|
|
|
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)) {
|
2019-03-04 19:53:35 -05:00
|
|
|
const [, body] = ev;
|
2019-01-06 14:26:18 -05:00
|
|
|
// ping
|
|
|
|
console.log("ws:Ping", body);
|
|
|
|
} else if (isWebSocketCloseEvent(ev)) {
|
|
|
|
// close
|
|
|
|
const { code, reason } = ev;
|
|
|
|
console.log("ws:Close", code, reason);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
main();
|