Apollo79
Apollo79

Reputation: 704

Deno.land WS module not found

I'm trying to set up a WebSocket server with deno. I've seen that there is / was a "ws" module in the standard library of deno, but in the current version there isn't one anymore.

Should I use the old std library or has this module moved somewhere else?

Upvotes: 1

Views: 839

Answers (1)

Zwiers
Zwiers

Reputation: 3668

ws was deprecated and then removed in [email protected], It is recommended to use Deno.upgradeWebSocket instead to upgrade incoming HTTP requests to WebSocket connections.

Here is an example of a basic WebSocket server and client in Deno (inspired by this post):

// server.js

async function handleConn(conn) {
  const httpConn = Deno.serveHttp(conn);
  
  for await (const e of httpConn) {
    e.respondWith(handle(e.request));
  }
}

function handle(req) {
  if (req.headers.get("upgrade") != "websocket") {
    return new Response("not trying to upgrade as websocket.");
  }

  // Upgrade the incoming HTTP request to a WebSocket connection
  const { socket, response } = Deno.upgradeWebSocket(req);
  socket.onopen = () => console.log("socket opened");
  socket.onmessage = (e) => {
    console.log("socket message:", e.data);
    socket.send(new Date().toString());
  };
  socket.onerror = (e) => console.log("socket errored:", e.message);
  socket.onclose = () => console.log("socket closed");

  return response;
}

const listener = Deno.listen({ hostname: "localhost", port: 8080 });

for await (const conn of listener) {
  handleConn(conn);
}
// client.js

const ws = new WebSocket("ws://localhost:8080/");

// Connection opened
ws.addEventListener('open', function (_event) {
    ws.send('Hello Server!');
});

expected output on server after running client.js:

socket opened
socket message: Hello Server!

Upvotes: 5

Related Questions