Bird
Raised Fist0
Denoframework~15 mins

WebSocket server and client in Deno - Deep Dive

Choose your learning style10 modes available
Overview - WebSocket server and client
What is it?
WebSocket is a way for a web browser and a server to talk to each other in real time. Unlike regular web requests that ask and wait for answers, WebSocket keeps the connection open so both sides can send messages anytime. In Deno, you can create both the server and client parts to use WebSocket for live updates or chats. This helps build apps that feel fast and interactive.
Why it matters
Without WebSocket, web apps would have to keep asking the server if there is new information, which wastes time and data. WebSocket solves this by keeping a live connection open, so messages flow instantly both ways. This makes apps like games, chats, or live feeds work smoothly and feel more like real conversations. It changes how users experience the web by making it more responsive and lively.
Where it fits
Before learning WebSocket, you should understand basic networking and HTTP requests. Knowing how servers and clients communicate helps. After WebSocket, you can explore real-time frameworks, event-driven programming, and advanced protocols like WebRTC. WebSocket is a key step toward building interactive web apps and understanding modern web communication.
Mental Model
Core Idea
WebSocket is a two-way open phone line between a client and server that lets them talk instantly without hanging up after each message.
Think of it like...
Imagine a walkie-talkie between two friends. Once turned on, they can talk back and forth anytime without dialing again. This is like WebSocket keeping a channel open for quick chats.
Client ────────┐
               │
               │  Open connection
               │
Server ────────┘

Messages flow both ways anytime without reconnecting.
Build-Up - 7 Steps
1
FoundationUnderstanding WebSocket basics
🤔
Concept: WebSocket creates a persistent connection allowing two-way communication between client and server.
Normally, web clients send a request and wait for a response, then disconnect. WebSocket changes this by opening a connection that stays open. Both sides can send messages anytime without reconnecting. This is useful for live data like chat messages or game updates.
Result
You get a connection that stays open and lets messages flow instantly both ways.
Understanding that WebSocket keeps a connection open is key to seeing how it enables real-time communication.
2
FoundationSetting up a simple WebSocket server in Deno
🤔
Concept: Deno provides built-in support to create a WebSocket server that listens for client connections.
Use Deno's standard library to create an HTTP server that upgrades requests to WebSocket. When a client connects, the server can send and receive messages. Example: import { serve } from "https://deno.land/std@0.203.0/http/server.ts"; serve(async (req) => { const { socket, response } = Deno.upgradeWebSocket(req); socket.onmessage = (e) => { socket.send(`Echo: ${e.data}`); }; return response; });
Result
A server that accepts WebSocket connections and echoes back messages sent by clients.
Knowing how to upgrade HTTP requests to WebSocket connections is the foundation for building real-time servers.
3
IntermediateCreating a WebSocket client in Deno
🤔
Concept: Deno can also act as a WebSocket client to connect and communicate with servers.
Use the WebSocket constructor to connect to a server URL. Then listen for messages and send data. Example: const ws = new WebSocket("ws://localhost:8080"); ws.onopen = () => { ws.send("Hello server!"); }; ws.onmessage = (event) => { console.log("Received:", event.data); };
Result
A client that connects to a WebSocket server, sends a message, and logs responses.
Understanding the client side lets you build apps that can talk live with servers.
4
IntermediateHandling multiple clients on the server
🤔Before reading on: Do you think a WebSocket server handles each client with a separate connection or shares one connection for all? Commit to your answer.
Concept: A WebSocket server manages each client with its own connection object to keep conversations separate.
When multiple clients connect, the server gets a separate socket for each. You can store these sockets in a list or map to send messages to all or specific clients. Example: const clients = new Set(); serve((req) => { const { socket, response } = Deno.upgradeWebSocket(req); clients.add(socket); socket.onclose = () => clients.delete(socket); socket.onmessage = (e) => { for (const client of clients) { client.send(`Broadcast: ${e.data}`); } }; return response; });
Result
The server can broadcast messages to all connected clients separately.
Knowing that each client has its own connection helps design features like chat rooms or live updates.
5
IntermediateManaging connection lifecycle and errors
🤔Before reading on: Should a WebSocket server ignore errors or handle them to keep running smoothly? Commit to your answer.
Concept: Properly handling connection open, close, and error events keeps the server stable and responsive.
Listen for 'close' and 'error' events on sockets. Clean up closed connections and log errors. Example: socket.onclose = () => { clients.delete(socket); console.log('Client disconnected'); }; socket.onerror = (e) => { console.error('Socket error:', e.message); };
Result
The server stays stable and cleans up resources when clients disconnect or errors occur.
Handling lifecycle events prevents resource leaks and keeps the server reliable.
6
AdvancedScaling WebSocket servers with Deno
🤔Before reading on: Do you think a single Deno WebSocket server can handle thousands of clients easily, or do you need special strategies? Commit to your answer.
Concept: Scaling WebSocket servers requires managing resources, load balancing, and possibly multiple server instances.
A single server can handle many clients but has limits. Use techniques like clustering, distributing clients across servers, or using message brokers to scale. Deno's async model helps but external tools may be needed for very large apps.
Result
You understand that scaling WebSocket servers involves more than just code; it needs architecture planning.
Knowing the limits of a single server helps plan for real-world apps that grow beyond simple demos.
7
ExpertWebSocket internals and protocol details
🤔Before reading on: Do you think WebSocket messages are always text, or can they be binary too? Commit to your answer.
Concept: WebSocket protocol defines a handshake, framing, and supports both text and binary messages with control frames for connection management.
WebSocket starts with an HTTP upgrade handshake. Then messages are sent in frames with headers indicating type and length. Frames can be text or binary. Control frames manage ping/pong to keep connection alive. Understanding this helps debug and optimize.
Result
You gain deep insight into how WebSocket works under the hood beyond simple message sending.
Understanding protocol details helps troubleshoot issues and optimize performance in production.
Under the Hood
WebSocket begins as a normal HTTP request with an 'Upgrade' header asking the server to switch protocols. The server responds agreeing to upgrade, and the connection switches from HTTP to WebSocket. After that, both client and server send messages in frames over the same TCP connection without closing it. Frames have headers describing message type and length. Control frames like ping and pong keep the connection alive and detect broken links. This persistent connection allows instant two-way communication.
Why designed this way?
WebSocket was designed to overcome the limitations of HTTP's request-response model, which is inefficient for real-time apps. By upgrading an HTTP connection, it reuses existing infrastructure and firewalls without new ports. The framing protocol allows flexible message types and control signals. Alternatives like polling were slower and wasteful, so WebSocket provides a standardized, efficient way to do live communication.
┌───────────────┐       HTTP Upgrade Request       ┌───────────────┐
│   Client      │─────────────────────────────────▶│   Server      │
│ (HTTP Request)│                                 │ (HTTP Response)│
└───────────────┘                                 └───────────────┘
          │                                                 │
          │               HTTP Upgrade Response            │
          │◀────────────────────────────────────────────────┤
          │                                                 │
          │               WebSocket Connection Established │
          │────────────────────────────────────────────────▶│
          │                                                 │
          │◀────────────────────────────────────────────────│
          │                                                 │
          │   ┌───────────────┐      ┌───────────────┐     │
          │   │ Text/Binary   │◀────▶│ Text/Binary   │     │
          │   │   Frames      │      │   Frames      │     │
          │   └───────────────┘      └───────────────┘     │
          │                                                 │
          │   Control Frames: Ping/Pong to keep alive       │
          │────────────────────────────────────────────────▶│
          │◀────────────────────────────────────────────────│
Myth Busters - 4 Common Misconceptions
Quick: Does WebSocket automatically reconnect if the connection drops? Commit to yes or no.
Common Belief:WebSocket connections automatically reconnect if they drop.
Tap to reveal reality
Reality:WebSocket does not reconnect automatically; the client or server must handle reconnection logic explicitly.
Why it matters:Assuming automatic reconnection can cause apps to silently stop receiving updates, leading to poor user experience.
Quick: Can WebSocket only send text messages? Commit to yes or no.
Common Belief:WebSocket can only send text messages between client and server.
Tap to reveal reality
Reality:WebSocket supports both text and binary messages, allowing flexible data formats like images or files.
Why it matters:Limiting to text wastes opportunities to send efficient binary data, reducing performance and capability.
Quick: Is WebSocket just a fancy HTTP request? Commit to yes or no.
Common Belief:WebSocket is just a special kind of HTTP request.
Tap to reveal reality
Reality:WebSocket starts as an HTTP request but then upgrades to a different protocol with persistent two-way communication.
Why it matters:Thinking it's just HTTP leads to misunderstanding its persistent nature and how to manage connections properly.
Quick: Does a WebSocket server share one connection for all clients? Commit to yes or no.
Common Belief:A WebSocket server uses a single connection to communicate with all clients.
Tap to reveal reality
Reality:Each client has its own separate WebSocket connection with the server.
Why it matters:Misunderstanding this can cause bugs in message routing and client management.
Expert Zone
1
WebSocket connections can be proxied through HTTP/2 or HTTP/3 tunnels, but this requires special handling and is not transparent.
2
The ping/pong control frames are essential for detecting dead connections but must be managed carefully to avoid false disconnects.
3
Message fragmentation allows sending very large messages in parts, but handling fragments correctly is often overlooked.
When NOT to use
WebSocket is not ideal for simple request-response apps or where HTTP/2 server push suffices. For peer-to-peer communication, WebRTC is better. For very high-frequency messaging, specialized protocols like MQTT or custom TCP may be preferred.
Production Patterns
In production, WebSocket servers often run behind load balancers that support sticky sessions or use shared state via Redis to coordinate clients. Message brokers or pub/sub systems handle broadcasting. Clients implement reconnection and exponential backoff. Security uses TLS (wss://) and origin checks.
Connections
HTTP/2 Server Push
Related protocol for pushing data from server to client without client request.
Understanding WebSocket helps grasp how HTTP/2 server push also aims to reduce latency but with different tradeoffs.
Event-Driven Programming
WebSocket communication relies on events like message, open, close, and error.
Knowing event-driven patterns clarifies how WebSocket apps react to asynchronous data flows.
Telephone Call
Both maintain an open two-way channel for conversation.
Recognizing WebSocket as a live conversation channel helps design better interactive apps.
Common Pitfalls
#1Not handling WebSocket connection close events.
Wrong approach:socket.onmessage = (e) => { console.log(e.data); };
Correct approach:socket.onmessage = (e) => { console.log(e.data); }; socket.onclose = () => { console.log('Connection closed'); };
Root cause:Beginners often forget to listen for close events, causing resource leaks or stale UI states.
#2Sending messages before the connection is open.
Wrong approach:const ws = new WebSocket(url); ws.send('Hello');
Correct approach:const ws = new WebSocket(url); ws.onopen = () => { ws.send('Hello'); };
Root cause:Trying to send messages immediately without waiting for the connection to open causes errors.
#3Assuming WebSocket messages are always strings.
Wrong approach:socket.onmessage = (e) => { processText(e.data); };
Correct approach:socket.onmessage = (e) => { if (typeof e.data === 'string') { processText(e.data); } else { processBinary(e.data); } };
Root cause:Ignoring binary message types leads to crashes or ignored data.
Key Takeaways
WebSocket creates a persistent, two-way connection between client and server for instant communication.
Deno supports both WebSocket servers and clients with simple APIs to build real-time apps.
Each client connection is separate, allowing servers to manage many clients independently.
Handling connection lifecycle events and errors is crucial for stable WebSocket applications.
Understanding the WebSocket protocol internals helps optimize and debug real-world systems.

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