Bird
Raised Fist0
Computer Networksknowledge~10 mins

WebSockets for real-time communication in Computer Networks - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - WebSockets for real-time communication
Client sends HTTP request to server
↓
Server responds with HTTP 101 Switching Protocols
↓
WebSocket connection established
↓
Client and Server exchange messages anytime
↓
Connection stays open until closed by either side
↓
Connection closed
The client starts by requesting to upgrade to WebSocket. The server agrees, and then both keep the connection open to send messages instantly until one closes it.
Execution Sample
Computer Networks
Client: Send HTTP Upgrade request
Server: Respond with 101 Switching Protocols
Client & Server: Exchange messages freely
Client or Server: Close connection
Shows the steps to establish and use a WebSocket connection for real-time message exchange.
Analysis Table
StepActionMessage TypeResultConnection State
1Client sends HTTP Upgrade requestHTTP RequestRequest to switch to WebSocketConnecting
2Server responds with 101 Switching ProtocolsHTTP ResponseAgrees to upgradeConnecting
3Connection upgraded to WebSocketProtocol SwitchConnection establishedOpen
4Client sends messageWebSocket FrameMessage received by serverOpen
5Server sends messageWebSocket FrameMessage received by clientOpen
6Client or Server sends close frameWebSocket Close FrameConnection closing initiatedClosing
7Connection closedNoneConnection fully closedClosed
💡 Connection closes when either client or server sends a close frame, ending the session.
State Tracker
VariableStartAfter Step 3After Step 4After Step 6Final
Connection StateDisconnectedOpenOpenClosingClosed
Messages Sent001 (client)1 (client)1 (client)
Messages Received0001 (client)1 (client)
Key Insights - 3 Insights
Why does the connection stay open after the initial HTTP handshake?
Because after the server sends the 101 Switching Protocols response (see execution_table step 2), the protocol changes from HTTP to WebSocket, which keeps the connection open for continuous message exchange.
What happens if the client sends a message before the server agrees to upgrade?
Messages can only be sent after the connection is upgraded (step 3). Sending messages before that would fail because the connection is still HTTP and not ready for WebSocket frames.
How does the connection close properly?
Either side sends a WebSocket Close Frame (step 6), signaling the intent to close. Both sides then close the connection cleanly (step 7).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the connection state after the server sends the 101 Switching Protocols response?
AConnecting
BOpen
CClosed
DClosing
💡 Hint
Check the 'Connection State' column at step 2 in the execution_table.
At which step does the client first send a WebSocket message?
AStep 3
BStep 2
CStep 4
DStep 6
💡 Hint
Look for the first 'WebSocket Frame' sent by the client in the execution_table.
If the client closes the connection at step 6, what is the connection state immediately after?
AClosed
BClosing
COpen
DConnecting
💡 Hint
Refer to the 'Connection State' column at step 6 in the execution_table.
Concept Snapshot
WebSockets start with an HTTP Upgrade request.
Server responds with 101 Switching Protocols to switch protocols.
Connection stays open for two-way real-time messages.
Messages are sent as WebSocket frames.
Connection closes when either side sends a close frame.
Full Transcript
WebSockets begin when a client sends an HTTP request asking to upgrade the connection. The server replies with a 101 Switching Protocols response to agree. After this, the connection changes from HTTP to WebSocket and stays open. Both client and server can send messages anytime without waiting. This allows real-time communication. The connection remains open until one side sends a close frame, which starts the closing process. Finally, the connection closes fully. This process enables fast, continuous data exchange between client and server.

Practice

(1/5)
1. What is the main advantage of using WebSockets for communication between a client and a server?
easy
A. They only allow one-way communication from server to client.
B. They allow real-time, two-way communication without repeatedly opening new connections.
C. They require a new connection for every message sent.
D. They work only for static web pages without interaction.

Solution

  1. Step 1: Understand WebSocket communication

    WebSockets keep a single connection open for continuous two-way data exchange.
  2. Step 2: Compare with other methods

    Unlike HTTP requests, WebSockets avoid opening new connections for each message.
  3. Final Answer:

    They allow real-time, two-way communication without repeatedly opening new connections. -> Option B
  4. Quick Check:

    Two-way real-time communication = They allow real-time, two-way communication without repeatedly opening new connections. [OK]
Hint: WebSockets keep one open connection for instant two-way chat [OK]
Common Mistakes:
  • Thinking WebSockets only send data one way
  • Confusing WebSockets with HTTP polling
  • Assuming new connection per message
2. Which of the following is the correct way to create a WebSocket connection in JavaScript?
easy
A. const socket = new WebSocket('http://example.com');
B. const socket = WebSocket.connect('ws://example.com');
C. const socket = WebSocket('https://example.com');
D. const socket = new WebSocket('ws://example.com');

Solution

  1. Step 1: Identify correct WebSocket URL scheme

    WebSocket URLs start with ws:// or wss:// for secure connections.
  2. Step 2: Check JavaScript syntax

    The correct syntax uses new WebSocket(url) with the ws:// scheme.
  3. Final Answer:

    const socket = new WebSocket('ws://example.com'); -> Option D
  4. Quick Check:

    WebSocket URL starts with ws:// = const socket = new WebSocket('ws://example.com'); [OK]
Hint: WebSocket URLs start with ws:// or wss:// [OK]
Common Mistakes:
  • Using http:// or https:// instead of ws://
  • Calling WebSocket without new keyword
  • Using incorrect method like WebSocket.connect
3. Consider this JavaScript code snippet using WebSocket:
const socket = new WebSocket('ws://example.com');
socket.onopen = () => socket.send('Hello');
socket.onmessage = (event) => console.log(event.data);

What will happen when the connection opens?
medium
A. The message 'Hello' is sent to the server, and incoming messages are logged.
B. The message 'Hello' is logged to the console, but nothing is sent.
C. An error occurs because send cannot be called on open event.
D. Nothing happens until the server sends a message first.

Solution

  1. Step 1: Analyze the onopen event handler

    When the WebSocket connection opens, it sends the string 'Hello' to the server.
  2. Step 2: Analyze the onmessage event handler

    Any message received from the server is logged to the console.
  3. Final Answer:

    The message 'Hello' is sent to the server, and incoming messages are logged. -> Option A
  4. Quick Check:

    Send on open + log messages = The message 'Hello' is sent to the server, and incoming messages are logged. [OK]
Hint: onopen sends, onmessage logs incoming data [OK]
Common Mistakes:
  • Thinking send cannot be called on open
  • Confusing logging sent message vs received message
  • Assuming no action until server sends first
4. A developer wrote this code to open a WebSocket and send a message:
const socket = new WebSocket('ws://example.com');
socket.send('Hi');

What is the problem with this code?
medium
A. The send method is called before the connection is open.
B. The URL should start with https:// instead of ws://.
C. The WebSocket constructor requires a callback function.
D. The message 'Hi' must be sent as an object, not a string.

Solution

  1. Step 1: Check WebSocket connection timing

    The send method must be called only after the connection is open.
  2. Step 2: Identify error in code

    Calling send immediately after creating the socket tries to send before connection is ready, causing an error.
  3. Final Answer:

    The send method is called before the connection is open. -> Option A
  4. Quick Check:

    send before open causes error = The send method is called before the connection is open. [OK]
Hint: Wait for onopen event before sending messages [OK]
Common Mistakes:
  • Using https:// instead of ws:// for WebSocket URL
  • Expecting constructor to take a callback
  • Sending non-string data without serialization
5. You want to build a live sports score dashboard using WebSockets. Which approach best ensures the dashboard updates instantly and efficiently?
hard
A. Open a new WebSocket connection for each score update.
B. Use HTTP polling every 5 seconds to fetch the latest scores.
C. Open a WebSocket connection once and update scores as messages arrive.
D. Send all scores once when the page loads and never update.

Solution

  1. Step 1: Understand real-time update needs

    A live dashboard needs instant updates without delay or repeated connection overhead.
  2. Step 2: Evaluate options for efficiency

    Opening one WebSocket connection and receiving updates as messages is efficient and real-time.
  3. Step 3: Eliminate less efficient methods

    Polling causes delay and overhead; opening many connections wastes resources; sending once misses updates.
  4. Final Answer:

    Open a WebSocket connection once and update scores as messages arrive. -> Option C
  5. Quick Check:

    Single open connection + live updates = Open a WebSocket connection once and update scores as messages arrive. [OK]
Hint: One open WebSocket connection handles all live updates efficiently [OK]
Common Mistakes:
  • Using polling instead of WebSocket for real-time
  • Opening multiple connections unnecessarily
  • Not updating after initial data load
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