Bird
Raised Fist0
Denoframework~10 mins

WebSocket server and client in Deno - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - WebSocket server and client
Start Server
↓
Wait for Client Connection
↓
Client Connects
↓
Server and Client Exchange Messages
↓
Message Received?
↓
Process
↓
Send Response
↓
Repeat Message Exchange
↓
Close Connection
↓
End
The server starts and waits for clients. When a client connects, they exchange messages back and forth until the connection closes.
Execution Sample
Deno
import { WebSocketServer } from "https://deno.land/std/ws/mod.ts";

const server = new WebSocketServer(8080);
for await (const sock of server) {
  sock.send("Hello Client!");
  for await (const msg of sock) {
    sock.send(`Server got: ${msg}`);
  }
}
This code starts a WebSocket server on port 8080 that sends a greeting to each client and echoes back any messages it receives.
Execution Table
StepActionServer StateClient StateMessage SentMessage Received
1Server starts listening on port 8080ListeningDisconnected--
2Client connects to serverConnected to clientConnected to server--
3Server sends greetingConnectedConnectedHello Client!-
4Client receives greetingConnectedConnected-Hello Client!
5Client sends 'Hi Server!'ConnectedConnected-Hi Server!
6Server receives 'Hi Server!'ConnectedConnected-Hi Server!
7Server sends echo messageConnectedConnectedServer got: Hi Server!-
8Client receives echo messageConnectedConnected-Server got: Hi Server!
9Client sends 'Bye'ConnectedConnected-Bye
10Server receives 'Bye'ConnectedConnected-Bye
11Server sends echo messageConnectedConnectedServer got: Bye-
12Client receives echo messageConnectedConnected-Server got: Bye
13Client closes connectionListeningDisconnected--
14Server detects closed connectionListeningDisconnected--
💡 Connection closes after client sends 'Bye' and disconnects.
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 9After Step 11Final
serverStateListeningConnectedConnectedConnectedConnectedConnectedListening
clientStateDisconnectedConnectedConnectedConnectedConnectedConnectedDisconnected
lastMessageSent-Hello Client!-Server got: Hi Server!-Server got: Bye-
lastMessageReceived--Hi Server!-Bye--
Key Moments - 3 Insights
Why does the server send a message immediately after the client connects?
The server sends a greeting right after connection to confirm the link is open, as shown in step 3 of the execution_table.
How does the server know when the client has closed the connection?
The server detects the closed connection when no more messages come and the socket closes, as seen in step 14.
Why does the server echo back the client's messages?
Echoing messages confirms the server received them and keeps communication active, demonstrated in steps 7 and 11.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what message does the server send at step 7?
AServer got: Hi Server!
BHi Server!
CHello Client!
DServer got: Bye
💡 Hint
Check the 'Message Sent' column at step 7 in the execution_table.
At which step does the client first receive a message from the server?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Message Received' column for the client in the execution_table.
If the client never sends 'Bye', what would happen to the connection state?
AThe connection would close immediately
BThe server would close the connection
CThe connection would stay open
DThe client would disconnect automatically
💡 Hint
Refer to the variable_tracker for 'serverState' and 'clientState' after step 11.
Concept Snapshot
WebSocket server listens for clients.
Client connects and handshake completes.
Server and client exchange messages asynchronously.
Messages can be sent and received anytime while connected.
Connection closes when either side disconnects.
Use async loops to handle messages in Deno.
Full Transcript
This visual execution shows how a WebSocket server in Deno starts listening on port 8080. When a client connects, the server sends a greeting message. The client receives it and replies with messages like 'Hi Server!' and 'Bye'. The server receives each message and sends back an echo confirming receipt. This back-and-forth continues until the client closes the connection. The server detects the closure and stops communication. Variables like serverState and clientState track connection status, and messages sent and received are recorded step by step. This helps beginners see how WebSocket communication flows in real time.

Practice

(1/5)
1. What is the main purpose of using WebSocket in a Deno application?
easy
A. To keep a live connection open for instant two-way communication
B. To send emails from the server
C. To serve static HTML files
D. To run background tasks without user interaction

Solution

  1. Step 1: Understand WebSocket functionality

    WebSocket allows a continuous open connection between client and server for real-time data exchange.
  2. Step 2: Compare with other options

    Sending emails, serving static files, or running background tasks are unrelated to WebSocket's purpose.
  3. Final Answer:

    To keep a live connection open for instant two-way communication -> Option A
  4. Quick Check:

    WebSocket = live two-way connection [OK]
Hint: WebSocket means live chat-like connection [OK]
Common Mistakes:
  • Confusing WebSocket with HTTP request-response
  • Thinking WebSocket sends emails
  • Assuming WebSocket serves files
2. Which of the following is the correct way to upgrade an HTTP request to a WebSocket connection in Deno?
easy
A. const { socket, response } = WebSocket.upgrade(request);
B. const socket = new WebSocket(request);
C. const ws = new WebSocketServer(request);
D. const { socket, response } = Deno.upgradeWebSocket(request);

Solution

  1. Step 1: Recall Deno WebSocket upgrade syntax

    Deno uses Deno.upgradeWebSocket(request) to upgrade HTTP requests to WebSocket connections.
  2. Step 2: Check other options for correctness

    Options B, C, and D use incorrect constructors or methods not available in Deno's standard library.
  3. Final Answer:

    const { socket, response } = Deno.upgradeWebSocket(request); -> Option D
  4. Quick Check:

    Deno.upgradeWebSocket() = correct upgrade method [OK]
Hint: Use Deno.upgradeWebSocket() to upgrade requests [OK]
Common Mistakes:
  • Using new WebSocket() on server side
  • Calling non-existent WebSocketServer constructor
  • Mixing client WebSocket API with server upgrade
3. Given this Deno WebSocket server snippet, what will the server send back when a client sends 'hello'?
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onmessage = (e) => {
  socket.send(`Received: ${e.data}`);
};
medium
A. "hello"
B. "e.data"
C. "Received: hello"
D. No response sent

Solution

  1. Step 1: Analyze the onmessage handler

    When a message arrives, the server sends back a string with 'Received: ' plus the message content.
  2. Step 2: Substitute the client message

    Client sends 'hello', so server sends 'Received: hello'.
  3. Final Answer:

    "Received: hello" -> Option C
  4. Quick Check:

    Server echoes with prefix 'Received:' [OK]
Hint: Server sends back 'Received: ' plus client message [OK]
Common Mistakes:
  • Thinking server echoes raw message without prefix
  • Confusing e.data as string literal
  • Assuming no response is sent
4. What is wrong with this Deno WebSocket server code?
const { socket, response } = Deno.upgradeWebSocket(request);
socket.onmessage = (e) => {
  socket.send(e.data.toUpperCase());
};
return response;
medium
A. No error, code is correct
B. Not returning the response object
C. Missing await before Deno.upgradeWebSocket
D. Not handling socket.onopen event

Solution

  1. Step 1: Check upgradeWebSocket usage

    Deno.upgradeWebSocket is synchronous and returns socket and response correctly.
  2. Step 2: Verify response return and event handling

    The response is returned properly, and onopen event is optional, not required.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    Code follows correct WebSocket server pattern [OK]
Hint: upgradeWebSocket is synchronous; return response is required [OK]
Common Mistakes:
  • Adding unnecessary await to upgradeWebSocket
  • Forgetting to return response
  • Thinking onopen event is mandatory
5. You want to build a Deno WebSocket server that broadcasts any received message to all connected clients. Which approach correctly manages multiple clients?
hard
A. Use a single socket variable and overwrite it on each connection
B. Store all sockets in an array and loop to send messages to each socket
C. Create a new WebSocket server for each client connection
D. Send messages only to the last connected client

Solution

  1. Step 1: Understand broadcasting concept

    Broadcasting means sending a message to all connected clients, so all sockets must be stored.
  2. 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.
  3. Final Answer:

    Store all sockets in an array and loop to send messages to each socket -> Option B
  4. Quick Check:

    Broadcast = send to all sockets stored [OK]
Hint: Keep all sockets in a list to broadcast messages [OK]
Common Mistakes:
  • Overwriting socket variable losing previous clients
  • Creating multiple servers instead of one
  • Sending messages only to one client
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard