Complete the code to create a WebSocket server that listens on port 8080.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { const { socket, response } = Deno.upgradeWebSocket(req); socket.onopen = () => console.log("[1] connected"); return response; }, { port: 8080 });
The onopen event triggers when a client connects to the WebSocket server. So, the message should say "Client connected".
Complete the code to send a message back to the client when a message is received.
socket.onmessage = (event) => {
console.log("Message received:", event.data);
socket.[1]("Echo: " + event.data);
};postMessage which is for Web Workers, not WebSocket.emit which is from other libraries like Socket.IO.The send method is used to send data back to the client over the WebSocket connection.
Fix the error in the client code to correctly open a WebSocket connection to ws://localhost:8080.
const socket = new WebSocket("[1]"); socket.onopen = () => console.log("Connected to server");
http:// instead of ws://.ftp:// which is unrelated.The WebSocket URL must start with ws:// for an unencrypted connection. Using http:// or other protocols will cause errors.
Fill both blanks to handle WebSocket errors and close events on the client side.
socket.[1] = (event) => { console.error("WebSocket error:", event); }; socket.[2] = () => { console.log("WebSocket connection closed"); };
onmessage with error or close events.onopen for error handling.onerror handles errors, and onclose handles when the connection closes.
Fill all three blanks to create a Deno WebSocket server that broadcasts received messages to all connected clients.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; const clients = new Set(); serve(async (req) => { const { socket, response } = Deno.upgradeWebSocket(req); clients.add(socket); socket.onmessage = (event) => { for (const client of clients) { if (client !== socket && client.readyState === [1]) { client.[2](event.data); } } }; socket.onclose = () => { clients.[3](socket); }; return response; }, { port: 8080 });
close instead of delete to remove clients.WebSocket.OPEN checks if the connection is open, send sends the message, and delete removes the socket from the set when closed.
