deno.land / x / opine@2.3.4 / examples / websockets / server.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/** * Run this example using: * * deno run --allow-read --allow-net ./examples/websockets/server.ts * * if have the repo cloned locally OR * * deno run --allow-read --allow-net https://raw.githubusercontent.com/cmorten/opine/main/examples/websockets/server.ts * * if you don't! * * After running the example, run the client with: * * deno run --allow-read --allow-net ./examples/websockets/client.ts * * (OR) * * deno run --allow-read --allow-net https://raw.githubusercontent.com/cmorten/opine/main/examples/websockets/server.ts */
import { opine } from "../../mod.ts";
const app = opine();const sockets = new Map<string, WebSocket>();
const handleWs = (socket: WebSocket) => { sockets.set(crypto.randomUUID(), socket);
socket.addEventListener("open", () => { socket.send("ping"); console.log("sent ping to client"); });
socket.addEventListener("close", (_) => { console.log("socket closed :("); });
socket.addEventListener("message", (e) => { if (e.data === "ping") { console.log("Received ping from client. Responding..."); socket.send("pong"); } else if (e.data === "pong") { console.log("Received ping response from client."); } });};
app.get("/ws", async (req, res, next) => { if (req.headers.get("upgrade") === "websocket") { const sock = req.upgrade(); await handleWs(sock); } else { res.send("You've gotta set the magic header..."); }
next();});
app.use((_, res, __) => { res.setHeader("access-control-allow-origin", "*"); res.setHeader( "access-control-expose-headers", "Upgrade,sec-websocket-accept,connection", );
res.send();});
app.listen(3000, () => { console.log("Opine listening on port 3000.");});
opine

Version Info

Tagged at
2 years ago