sholladay / pogo

Server framework for Deno
Mozilla Public License 2.0
482 stars 33 forks source link

Support for WebSockets #7

Open EricEisaman opened 4 years ago

EricEisaman commented 4 years ago

Do you have an idiomatic example for establishing a WebSocket with pogo?

sholladay commented 4 years ago

Hi and thanks for checking out Pogo!

I have not yet tried to use WebSockets with Deno. There is no API in Pogo for it currently, but I am open to adding support for WebSockets. That will happen faster if you can make a pull request, otherwise I will probably get around to it eventually.

Here are some relevant resources:

EricEisaman commented 4 years ago

Thanks. I will take a look.

headdu commented 4 years ago

Hey!

I'm still learning Deno but I have something monkey patched working locally for me.

I'm not confident enough yet to write a PR but I'll leave here what I have for others that may want to test this out.

import this from deno's std

import {
  acceptWebSocket,
  acceptable,
} from "https://deno.land/std/ws/mod.ts";

My function to create the websockets is this one (Connection in this context is a class I created to manage all messages)

async function handleWebsocket(req: ServerRequest) {
  const { headers, conn } = req;

  try {
    const websocket = await acceptWebSocket({
      conn,
      headers,
      bufReader: req.r,
      bufWriter: req.w,
    });

    new Connection(websocket);
  } catch (err) {
    console.error(`failed to accept websocket: ${err}`);
  }
}

Initialize Pogo as per the Readme

const server = pogo.server({ port: 8080 });

server.router.get("/", (req: any) => {
  console.log(`request received`);

  return "Hello!";
});

And now for the important bit. Instead of starting pogo normally, I created a different function just to check if it is a valid websocket request, if it is manage it with the previously created function

async function start() {
  const serverr = serve({
    hostname: "localhost",
    port: 8080,
  });
  server.raw = serverr;
  for await (const request of serverr) {
    if (acceptable(request)) {
      await handleWebsocket(request);
    } else {
      server.respond(request);
    }
  }
}

await start();