generated at
denoでWebSocketを実装した
denoWebSocketサーバーを実装したkeroxp 2018/12/28
deno_stdにhttpサーバができてたからWebSocketの仕様読みながら実装した
2018/12/27 ~ 2018/12/28で動くようになった
多分世界で最初だと思います
こういうふうに書ける
main.ts
import {serve} from "https://deno.land/x/net/http.ts"; import {acceptWebSocket, isWebSocketCloseEvent, isWebSocketPingEvent} from "https://raw.githubusercontent.com/keroxp/deno-ws/master/ws.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();
wscatで繋ぐとエコーサーバになる
bash
$ wscat -c localhost:8080/ws connected (press CTRL+C to quit) > hello < hello >