diff options
| author | Yusuke Sakurai <kerokerokerop@gmail.com> | 2019-01-07 04:26:18 +0900 |
|---|---|---|
| committer | Ryan Dahl <ry@tinyclouds.org> | 2019-01-06 14:26:18 -0500 |
| commit | 7907bfc4c91f5287237d87571d1933db4ae7a4fa (patch) | |
| tree | 6c14062ed9e08bb7543053b760dacd043acd874d /examples | |
| parent | c164e696d7f924fe785421058d834934b7014429 (diff) | |
Add web socket module (denoland/deno_std#84)
Original: https://github.com/denoland/deno_std/commit/2606e295c77fb9d5796d527ed15f2dab3de1a696
Diffstat (limited to 'examples')
| -rw-r--r-- | examples/ws.ts | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/examples/ws.ts b/examples/ws.ts new file mode 100644 index 000000000..f8e711c49 --- /dev/null +++ b/examples/ws.ts @@ -0,0 +1,39 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { serve } from "https://deno.land/x/net/http.ts"; +import { + acceptWebSocket, + isWebSocketCloseEvent, + isWebSocketPingEvent +} from "https://deno.land/x/net/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 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)) { + 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(); |
