WebSocket lets your app talk to a server in real-time. It keeps the connection open so messages can flow back and forth instantly.
WebSocket server and client in Deno
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { const { socket, response } = Deno.upgradeWebSocket(req); socket.onopen = () => { socket.send("Hello from server!"); }; socket.onmessage = (event) => { socket.send(`You said: ${event.data}`); }; socket.onclose = () => { console.log("WebSocket closed"); }; return response; }, { port: 8080 });
Use Deno.upgradeWebSocket(req) to turn an HTTP request into a WebSocket connection.
Handle events like onopen, onmessage, and onclose on the socket.
const ws = new WebSocket("ws://localhost:8080"); ws.onopen = () => { ws.send("Hi server!"); }; ws.onmessage = (event) => { console.log("Message from server:", event.data); };
socket.onmessage = (event) => {
if (event.data === "ping") {
socket.send("pong");
}
};This Deno program starts a WebSocket server on port 8080. It welcomes clients, echoes messages back with a prefix, and logs connection events.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; console.log("WebSocket server running on ws://localhost:8080"); serve(async (req) => { if (req.headers.get("upgrade") !== "websocket") { return new Response("Not a websocket request", { status: 400 }); } const { socket, response } = Deno.upgradeWebSocket(req); socket.onopen = () => { console.log("Client connected"); socket.send("Welcome to the WebSocket server!"); }; socket.onmessage = (event) => { console.log("Received from client:", event.data); socket.send(`Server says: You sent '${event.data}'`); }; socket.onclose = () => { console.log("Client disconnected"); }; socket.onerror = (e) => { console.error("WebSocket error:", e); }; return response; }, { port: 8080 });
WebSocket connections start as HTTP requests and then upgrade to a persistent connection.
Always check if the request wants to upgrade to WebSocket before upgrading.
Use console logs to see connection and message events during development.
WebSocket keeps a live connection open for instant two-way communication.
Deno uses Deno.upgradeWebSocket() to create WebSocket servers.
Clients use the WebSocket API to connect and talk to the server.
Practice
Solution
Step 1: Understand WebSocket functionality
WebSocket allows a continuous open connection between client and server for real-time data exchange.Step 2: Compare with other options
Sending emails, serving static files, or running background tasks are unrelated to WebSocket's purpose.Final Answer:
To keep a live connection open for instant two-way communication -> Option AQuick Check:
WebSocket = live two-way connection [OK]
- Confusing WebSocket with HTTP request-response
- Thinking WebSocket sends emails
- Assuming WebSocket serves files
Solution
Step 1: Recall Deno WebSocket upgrade syntax
Deno usesDeno.upgradeWebSocket(request)to upgrade HTTP requests to WebSocket connections.Step 2: Check other options for correctness
Options B, C, and D use incorrect constructors or methods not available in Deno's standard library.Final Answer:
const { socket, response } = Deno.upgradeWebSocket(request); -> Option DQuick Check:
Deno.upgradeWebSocket() = correct upgrade method [OK]
- Using new WebSocket() on server side
- Calling non-existent WebSocketServer constructor
- Mixing client WebSocket API with server upgrade
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onmessage = (e) => {
socket.send(`Received: ${e.data}`);
};Solution
Step 1: Analyze the onmessage handler
When a message arrives, the server sends back a string with 'Received: ' plus the message content.Step 2: Substitute the client message
Client sends 'hello', so server sends 'Received: hello'.Final Answer:
"Received: hello" -> Option CQuick Check:
Server echoes with prefix 'Received:' [OK]
- Thinking server echoes raw message without prefix
- Confusing e.data as string literal
- Assuming no response is sent
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onmessage = (e) => {
socket.send(e.data.toUpperCase());
};
return response;Solution
Step 1: Check upgradeWebSocket usage
Deno.upgradeWebSocket is synchronous and returns socket and response correctly.Step 2: Verify response return and event handling
The response is returned properly, and onopen event is optional, not required.Final Answer:
No error, code is correct -> Option AQuick Check:
Code follows correct WebSocket server pattern [OK]
- Adding unnecessary await to upgradeWebSocket
- Forgetting to return response
- Thinking onopen event is mandatory
Solution
Step 1: Understand broadcasting concept
Broadcasting means sending a message to all connected clients, so all sockets must be stored.Step 2: Evaluate options for managing clients
Store all sockets in an array and loop to send messages to each socket stores sockets in an array and loops to send messages, which is correct. Options A, B, and D do not support broadcasting properly.Final Answer:
Store all sockets in an array and loop to send messages to each socket -> Option BQuick Check:
Broadcast = send to all sockets stored [OK]
- Overwriting socket variable losing previous clients
- Creating multiple servers instead of one
- Sending messages only to one client
Ready to prove it?
Pass the test and this pattern moves unknown
