griffin's blog

goggl.io day 4? chat

time for the first realtime feature of goggl.io

when I say realtime, I mean websockets instead of http

I'm pretty sure that's all I'm gonna need - websockets + http

no message queues/kafka/whatever nonsense

maybe html sse would be neat

in fact yeah that would make for a pretty cool chat app - who needs websockets when you have sse...

well...

websockets are fun and easy so...

here we go

  1. dual websocket/http server

its soooooo easy to have websockets and http in the same thing

idk what to even call the thing

src
|_index.tsx
|_http
   |_index.tsx -> `export default app`
|_ws
   |_index.tsx -> `Bun.serve({port: 8080, ...})`

index.tsx

import "./ws/index"

import app from "./http/index";
export default app;

beautiful!

bun run src/ws/index.tsx (just run the bun ws server) bun run src/http/index.tsx (just run hono) bun run src/index.tsx (run both)

  1. uhhh

i either had chat or bun cook me up a little websocket code

Bun.serve({
  port: 8080,
  fetch(req, server) {
    if (server.upgrade(req)) {
      return;
    }
    return new Response("Upgrade failed", { status: 500 });
  },
  websocket: {
    message(ws, message) {
      console.log(message)
    },
    open(ws) {
      console.log('connect')
    },
    close(ws, code, message) {
      console.log('close with code', code)
    },
    drain(ws) {
      console.log('drain?')
    },
  },
});
console.log('listening on port 8080 for ws')

now we just need a client