Intermediate
clideploy
HTTP Server: WebSockets
An example of a HTTP server that handles websocket requests.
Import the http server from std/http.
!--frsh-copybutton:1-->
import { serve } from "https://deno.land/std@0.184.0/http/server.ts";
To start the server on the default port, call `serve` with the handler.
!--frsh-copybutton:2-->
serve((req) => {
First, we verify if the client is negotiating to upgrade to websockets. If not, we can give a status of 501 to specify we don't support plain http requests.
!--frsh-copybutton:3-->
if (req.headers.get("upgrade") != "websocket") {
return new Response(null, { status: 501 });
}
We can then upgrade the request to a websocket
!--frsh-copybutton:4-->
const { socket, response } = Deno.upgradeWebSocket(req);
We now have access to a standard websocket object. Let's handle the "open" event
!--frsh-copybutton:5-->
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.
!--frsh-copybutton:6-->
socket.addEventListener("message", (event) => {
if (event.data === "ping") {
socket.send("pong");
}
});
Lastly we return the response created from upgradeWebSocket.
!--frsh-copybutton:7-->
return response;
});
Run this example locally using the Deno CLI:
deno run --allow-net https://examples.deno.land/http-server-websocket.ts
Additional resources: