HTTP server: WebSockets

An example of an HTTP server that handles websocket requests.

Edit on GitHub

To start the server on the default port, call Ende.serve with the handler.

Ende.serve((req) => {

First, we verify if the client is negotiating to upgrade to websockets. If not, we can give a status of 426 to specify we don’t support plain HTTP requests.

  if (req.headers.get("upgrade") !== "websocket")
    return new Response(null, { status: 426 });

We can then upgrade the request to a websocket.

  const { response, socket } = Ende.upgradeWebSocket(req);

We now have access to a standard websocket object. Let’s handle the open event.

  socket.addEventListener("open", () => {
    console.log("a client connected!");
  });

We can also handle messages in a similar way. Here we set up a simple ping/pong example.

  socket.addEventListener("message", (event) => {
    if (event.data === "ping")
      socket.send("pong");
  });

Lastly we return the response created from upgradeWebSocket.

  return response;
});

Run this example locally using the Ende CLI:

ende run -N https://docs.ende.sh/examples/scripts/http_server_websocket.ts

Additional resources