diff options
| author | Adam Soltys <[email protected]> | 2024-08-26 16:28:30 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2024-08-26 16:28:30 -0700 |
| commit | 00e43ddc0bf3d6dd719fc9295d156567fa2fecfb (patch) | |
| tree | 9719782a64056ff904c0053223d70547bb7f398c /lib/sockets.js | |
| parent | 3c611a4e6fbb31fa7d8e32ed256037c45aca1d6d (diff) | |
| download | coinos-server-00e43ddc0bf3d6dd719fc9295d156567fa2fecfb.tar.gz coinos-server-00e43ddc0bf3d6dd719fc9295d156567fa2fecfb.zip | |
switch to bun
Diffstat (limited to 'lib/sockets.js')
| -rw-r--r-- | lib/sockets.js | 51 |
1 files changed, 29 insertions, 22 deletions
diff --git a/lib/sockets.js b/lib/sockets.js index 2339c06e..b1fc719c 100644 --- a/lib/sockets.js +++ b/lib/sockets.js @@ -67,20 +67,21 @@ let track = async (ws, token) => { ws.user = user; }; -export async function socketServer(app) { - let seconds = (n, d = new Date()) => d.setSeconds(d.getSeconds() - n) && d; - - app.get("/ws", { websocket: true }, (connection, req) => { - let { socket: ws } = connection; - connection.on("error", (e) => err(e.message)); - - const id = v4(); - ws.id = id; - ws.beats = 0; - ws.send(JSON.stringify({ type: "connected", data: id })); - all[id] = ws; - - ws.on("message", async (message) => { +console.log("starting socket server"); +Bun.serve({ + hostname: "0.0.0.0", + port: 3120, + fetch(req, server) { + console.log("here we go"); + // upgrade the request to a WebSocket + if (server.upgrade(req)) { + console.log("UPGRADING"); + return; // do not return a Response + } + return new Response("Upgrade failed", { status: 500 }); + }, + websocket: { + async message(ws, message) { let type, data; try { @@ -128,11 +129,17 @@ export async function socketServer(app) { default: warn("received socket message of unknown type", type, data); } - }); - - ws.on("error", (e) => {}); - - ws.on("close", function (code, reason) { + }, + open(ws) { + console.log("OPENING"); + const id = v4(); + ws.id = id; + ws.beats = 0; + ws.send(JSON.stringify({ type: "connected", data: id })); + all[id] = ws; + }, + close(ws) { + let { id } = ws; try { const uid = users[id]; if (store.sockets[uid] && store.sockets[uid][id]) { @@ -143,9 +150,9 @@ export async function socketServer(app) { } catch (e) { err("problem closing socket", e.message); } - }); - }); -} + }, + }, +}); export let sendHeartbeat = () => { for (const uid in store.sockets) { |
