denoでWebSocketを実装した
2018/12/27 ~ 2018/12/28で動くようになった
多分世界で最初だと思います
こういうふうに書ける
code:main.ts
async function main() {
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") {
(async () => {
const err, sock = await acceptWebSocket(req); if (err) return;
console.log("socket connected!");
for await (const ev of sock.handle()) {
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);
}
}
})();
}
}
}
main();
code:bash
$ wscat -c localhost:8080/ws
connected (press CTRL+C to quit)
hello
< hello