-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathws.ts
60 lines (55 loc) · 1.17 KB
/
ws.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
import type { ActorContext } from "@rivet-gg/actor-core";
import { Hono } from "hono";
import { upgradeWebSocket } from "hono/deno";
// Setup Hono app
const app = new Hono();
app.get("/health", (c) => {
return c.text("ok");
});
app.get(
"/ws",
upgradeWebSocket((c) => {
return {
onOpen(_event, ws) {
ws.send(
JSON.stringify([
"init",
{
forwardedFor: c.header("x-forwarded-for"),
},
]),
);
},
onMessage(event, ws) {
if (typeof event.data === "string") {
const [eventType, data] = JSON.parse(
event.data.slice(0, 2 ** 13),
);
switch (eventType) {
case "ping":
ws.send(JSON.stringify(["pong", data]));
break;
default:
console.warn("unknown event", eventType);
break;
}
}
},
};
}),
);
// Start server
export default {
async start(ctx: ActorContext) {
// Find port
const portEnv = Deno.env.get("PORT_HTTP");
if (!portEnv) {
throw new Error("missing PORT_HTTP");
}
const port = Number.parseInt(portEnv);
// Start server
console.log(`Listening on port ${port}`);
const server = Deno.serve({ port }, app.fetch);
await server.finished;
},
};