How to Use WebSocket in Deno: Simple Guide with Example
In Deno, you can use the built-in
WebSocket API to create WebSocket servers and clients. Use Deno.upgradeWebSocket() in an HTTP server to upgrade connections to WebSocket, then handle messages with event listeners.Syntax
To use WebSocket in Deno, you typically create an HTTP server and upgrade the connection to a WebSocket using Deno.upgradeWebSocket(request). This returns a WebSocket object with event handlers like onopen, onmessage, and onclose.
You send messages with websocket.send() and close the connection with websocket.close().
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve((req) => { const { socket, response } = Deno.upgradeWebSocket(req); socket.onopen = () => { console.log("WebSocket connection opened"); }; socket.onmessage = (event) => { console.log("Received message:", event.data); socket.send(`Echo: ${event.data}`); }; socket.onclose = () => { console.log("WebSocket connection closed"); }; return response; }, { port: 8080 });
Example
This example creates a WebSocket server on port 8080 that echoes back any message it receives. It logs connection open, messages, and close events to the console.
typescript
import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve((req) => { if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") { return new Response("Not a websocket request", { status: 400 }); } const { socket, response } = Deno.upgradeWebSocket(req); socket.onopen = () => { console.log("Client connected"); }; socket.onmessage = (event) => { console.log("Message from client:", event.data); socket.send(`Server echo: ${event.data}`); }; socket.onclose = () => { console.log("Client disconnected"); }; socket.onerror = (e) => { console.error("WebSocket error:", e); }; return response; }, { port: 8080 });
Output
Client connected
Message from client: Hello
Client disconnected
Common Pitfalls
- Not checking the upgrade header: Always verify the request has
upgrade: websocketheader before upgrading. - Forgetting to return the upgrade response: You must return the response from
Deno.upgradeWebSocket()to complete the handshake. - Not handling errors: Add an
onerrorhandler to catch connection issues. - Closing socket improperly: Use
socket.close()to close connections gracefully.
typescript
/* Wrong: Missing upgrade check and no error handler */ import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve((req) => { const { socket, response } = Deno.upgradeWebSocket(req); socket.onmessage = (e) => socket.send(e.data); return response; }, { port: 8080 }); /* Right: Check upgrade header and add error handler */ serve((req) => { if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") { return new Response("Not a websocket request", { status: 400 }); } const { socket, response } = Deno.upgradeWebSocket(req); socket.onerror = (e) => console.error("WebSocket error", e); socket.onmessage = (e) => socket.send(e.data); return response; }, { port: 8080 });
Quick Reference
Here is a quick summary of key WebSocket methods and events in Deno:
| Method/Event | Description |
|---|---|
| Deno.upgradeWebSocket(request) | Upgrades HTTP request to WebSocket connection |
| socket.onopen | Called when connection opens |
| socket.onmessage | Called when a message is received |
| socket.send(data) | Sends data to the client |
| socket.onclose | Called when connection closes |
| socket.onerror | Called on connection error |
| socket.close() | Closes the WebSocket connection |
Key Takeaways
Use Deno.upgradeWebSocket() inside an HTTP server to create WebSocket connections.
Always check the 'upgrade' header before upgrading to WebSocket.
Handle socket events like onopen, onmessage, onclose, and onerror for smooth communication.
Return the upgrade response to complete the WebSocket handshake.
Use socket.send() to send messages and socket.close() to close connections properly.