Understanding HTTP and WebSocket for Beginners: Run These 8 Python Codes to Grasp Network Communication Principles

When you watch videos, chat on WeChat, or check your delivery status, what are your phone and the server really “talking” about? In essence, all network interactions are driven by two types of “chatting rules”—HTTP is like “sending a text message,” where you send one message and wait for a reply before ending the conversation; WebSocket is like “making a phone call,” where once connected, you can chat anytime without waiting for the other party to start the conversation.

Today, without memorizing terminology, we will use Python code that beginners can run to help you dismantle the core principles of these two protocols. After reading, you will be able to practice hands-on and thoroughly understand how “network conversations” are implemented!

1. First, Understand 2 Core Concepts: No Need to Memorize, Just Look at the Examples

1. Simple Analogies

  • HTTP: One-way “question and answer.” The client (your phone/code) must first actively send a “request” before the server passively returns a “response.” Once done, the connection is terminated, and to talk again, you need to “redial.”
  • WebSocket: Two-way “continuous chatting.” First, upgrade the protocol by “knocking” through HTTP, and after establishing the connection, both the client and server can send messages at any time, maintaining the connection until actively disconnected.

2. Essential Differences for Beginners (Comparison Table)

Feature HTTP WebSocket
Chat Method You ask, I answer; cannot interrupt Two-way chat, can speak anytime
Connection Status Hang up after chatting, reconnect next time Once connected, stay online long-term
Real-time Performance Slow (requires repeated reconnections) Fast (server actively pushes)
Code Difficulty Super simple (3 lines of core code) A bit complex (needs to handle asynchronous)
Typical Scenarios Browsing web pages, checking data, downloading files Real-time chatting, online gaming, stock quotes

Preparation Work (Must Do)

First, install the required Python libraries. Open the terminal and copy-paste to execute:

pip install flask requests websockets  # Corresponding to: HTTP server, HTTP client, WebSocket

After successful installation, let’s start writing code!

2. HTTP Protocol: Write a “Question and Answer” Dialogue Yourself

HTTP is the most commonly used protocol. For example, when you open this article, your browser uses HTTP to request the “article content” from the server. We will write two programs: an HTTP server (to receive requests) and an HTTP client (to send requests), to intuitively experience the “request-response” process.

1. Write an HTTP Server: 3 Lines of Core Code to Receive Requests and Reply

Create a file <span>http_server.py</span>, which listens for client requests and returns greetings upon receiving them (comments detail every aspect so that beginners can understand each line):

# Import Flask library (lightweight HTTP server framework)
from flask import Flask, request

# Initialize HTTP server application (__name__ indicates the current file as the server entry)
app = Flask(__name__)

# Define HTTP interface: when the client accesses the "/hello" path, this function is triggered
@app.route('/hello', methods=['GET'])  # methods=['GET'] indicates it only accepts GET requests
def handle_hello_request():
    # Get the parameter "name" sent by the client from the request; defaults to "stranger" if not provided
    name = request.args.get('name', '陌生人')
    # Server returns response (this ends a conversation)
    return f"HTTP服务器回复:你好呀,{name}!"

# Start the server: host='0.0.0.0' allows access from computers/phones, port=5000 is the port number
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

2. Write an HTTP Client: 1 Line of Core Code to Send Requests and Receive Replies

Create a file <span>http_client.py</span>, which sends requests to the above server and receives and prints the response:

# Import requests library (specifically for sending HTTP requests)
import requests

# 1. Send a GET request to the HTTP server: specify server address + parameter name=小明
# Server address is http://localhost:5000 (localhost means local computer), interface path is /hello
response = requests.get(
    url='http://localhost:5000/hello',
    params={'name': '小明'}  # Parameter sent to the server
)

# 2. Print the response content returned by the server (response.text is the text data of the response)
print("客户端收到HTTP响应:", response.text)

# 3. Send another request (simulate multiple conversations; each time a new connection must be established)
response2 = requests.get(
    url='http://localhost:5000/hello',
    params={'name': '小红'}
)
print("客户端收到HTTP响应:", response2.text)

3. Running Steps + Expected Results (Follow the Order, You Won’t Go Wrong)

  1. 1. Start the HTTP server: run <span>http_server.py</span>, and the terminal displays “Running on http://0.0.0.0:5000” (indicating the server has started).
  2. 2. Run the HTTP client: open a new terminal and run <span>http_client.py</span>, and the terminal outputs:
客户端收到HTTP响应: HTTP服务器回复:你好呀,小明!
客户端收到HTTP响应: HTTP服务器回复:你好呀,小红!
  1. 3. Check the server logs: it will show two independent request records (after each request, the connection will automatically disconnect).

4. Core Principles of HTTP: Understanding the “Request-Response” Process from Code

  • • The client must first actively send a request (<span>requests.get()</span>), and only then will the server reply.
  • • Each request requires re-establishing the connection, and after the reply, it disconnects immediately; it cannot “actively talk to the client.”
  • • This is the “request-response model” of HTTP—like sending a text message; if you don’t send, the other party cannot actively send you a message (unless using polling, but essentially it still involves repeatedly sending requests).

3. WebSocket Protocol: Write a “Real-time Group Chat” Yourself to Experience Two-way Communication

WebSocket is suitable for real-time scenarios, such as WeChat chatting and online gaming. We will use the <span>websockets</span> library to write a “real-time group chat server” and “client” to feel the core feature of “both parties can send messages at any time.”

1. Write a WebSocket Server: Supports Multiple Clients and Can Actively Push Messages

Create a file <span>ws_server.py</span>, which receives messages from clients and broadcasts to all online clients (like group chat), with detailed comments for each step:

# Import asynchronous programming library (WebSocket needs to handle multiple clients asynchronously)
import asyncio
import websockets

# Store all online clients (for group chat broadcasting)
online_clients = set()

# This function is triggered for each client connection (handles communication with that client)
async def handle_client(websocket):
    # Client connection successful, add to "online list"
    online_clients.add(websocket)
    print(f"新客户端上线,当前在线:{len(online_clients)}人")
    
    try:
        # Loop to listen for messages sent by the client (continuously receive until the client disconnects)
        async for message in websocket:
            print(f"收到客户端消息:{message}")
            
            # 1. The server actively replies to that client (the core of two-way communication: the server can actively send messages)
            await websocket.send(f"服务器回复你:{message}")
            
            # 2. Broadcast the message to all online clients (group chat function: let others see the message)
            for client in online_clients:
                if client != websocket:  # Don't send to self
                    await client.send(f"群友说:{message}")
    finally:
        # Client disconnects, remove from "online list"
        online_clients.remove(websocket)
        print(f"客户端下线,当前在线:{len(online_clients)}人")

# Start the WebSocket server
async def start_ws_server():
    # Listen on local port 5001, path is /ws (clients must connect to this path)
    async with websockets.serve(handle_client, "localhost", 5001):
        print("WebSocket服务器启动成功,等待客户端连接...")
        await asyncio.Future()  # Keep the server running (won't exit automatically)

if __name__ == "__main__":
    # Run asynchronous function to start the server
    asyncio.run(start_ws_server())

2. Write a WebSocket Client: Can Send Messages and Receive Messages in Real-time

Create a file <span>ws_client.py</span>, which connects to the server and can input messages to send while receiving messages from the server/other clients in real-time (solving the common beginner fear of “asynchronous sending and receiving” issues):

import asyncio
import websockets

# Core logic of the client: connect to the server + send and receive messages
async def chat_client():
    # 1. Connect to the WebSocket server (protocol is ws://, not http://; path must match the server)
    async with websockets.connect("ws://localhost:5001/ws") as websocket:
        print("连接群聊成功!输入消息按回车发送(输入q退出):")
        
        # Sub-function 1: Handle "send message" (listen for user input)
        async def send_message():
            while True:
                message = input()  # Wait for user input
                if message == "q":  # Input q to exit
                    break
                await websocket.send(message)  # Send message to server
        
        # Sub-function 2: Handle "receive message" (real-time listen for server push)
        async def receive_message():
            while True:
                try:
                    # Continuously listen for server messages (won't block input)
                    response = await websocket.recv()
                    # Print received message without affecting subsequent input
                    print(f"\n收到消息:{response}\n请输入:", end="")
                except websockets.exceptions.ConnectionClosed:
                    print("\n服务器连接已断开")
                    break
        
        # Run "send" and "receive" tasks simultaneously (asynchronous core: both sides don't delay)
        await asyncio.gather(send_message(), receive_message())

if __name__ == "__main__":
    asyncio.run(chat_client())

3. Running Steps + Expected Results (Experience Real-time Group Chat)

  1. 1. Start the WebSocket server: run <span>ws_server.py</span>, and the terminal displays “WebSocket服务器启动成功,等待客户端连接…”.
  2. 2. Start multiple clients: open 2 new terminals and run <span>ws_client.py</span> in each, and each client displays “连接群聊成功!”.
  3. 3. Client 1 inputs “大家好,我是小明”:
  • • Client 1 immediately displays: 收到消息:服务器回复你:大家好,我是小明
  • • Client 2 immediately displays: 收到消息:群友说:大家好,我是小明
  • • Server terminal displays: 收到客户端消息:大家好,我是小明
  • 4. Client 2 inputs “你好呀小明!”:
    • • Both clients receive messages in real-time without needing to reconnect; the connection remains open.

    4. Core Principles of WebSocket: Understanding “Two-way Persistent Connection” from Code

    • • First, “handshake upgrade”: when the client connects, it sends an HTTP request, and the server responds with “protocol upgrade,” after which communication occurs using the WebSocket protocol.
    • • One connection, multiple communications: after the connection is established, <span>async for message in websocket</span> continuously listens without needing to reconnect.
    • • Two-way active: the server can actively <span>send()</span> messages (like broadcasting), and the client can also send messages at any time, which is “full-duplex communication.”

    4. Core Principle Comparison: Understanding the Essential Differences Between the Two Protocols Through Code

    Comparison Dimension HTTP Code Representation WebSocket Code Representation
    Connection Logic Each <span>requests.get()</span> rebuilds the connection, disconnects after use One <span>websockets.connect()</span>, long-term reuse
    Communication Trigger Only the client <span>get()</span>, the server then <span>return</span> Both the server <span>send()</span> and the client <span>send()</span> can
    Real-time Performance If the client does not send a request, it will not receive new messages The server pushes messages, and the client receives them instantly
    Resource Consumption High (repeatedly building connections) Low (connection reuse)

    Common Questions for Beginners (Pitfall Guide)

    1. 1. Why does WebSocket need to be asynchronous?Because the server needs to handle multiple clients simultaneously (for example, in group chat, when someone sends a message, others need to receive it in real-time), asynchronous allows “sending and receiving messages” without delay; synchronous code would block.
    2. 2. What to do if the port is occupied when running the code?Change <span>port=5000</span> to <span>port=5002</span> (just pick another unused number), and the client address must also be changed accordingly.
    3. 3. Why can’t HTTP be used for real-time chatting?For real-time communication, the client would need to send a request every second (polling); if the server has new messages, it replies, if not, it waits, which is slow and resource-consuming. It’s better to use WebSocket for a one-time connection.

    5. Summary for Beginners: When to Use HTTP and When to Use WebSocket?

    1. 1. Choose HTTP (90% of daily scenarios):
    • • Only need to “check data” or “submit data” (like checking the weather, logging in, downloading files).
    • • Don’t want to write complex code, seeking simplicity (<span>requests.get()</span><span> does it in one line).</span>
  • 2. Choose WebSocket (for real-time scenarios):
    • • Need “two-way real-time interaction” (like chatting, online gaming, real-time bullet screens).
    • • The server needs to actively push data (like stock quotes, delivery progress notifications).

    Remember: Modern apps often mix both protocols—using HTTP for login and page loading, and WebSocket for handling real-time messages (like WeChat, using HTTP for login and WebSocket for chatting).

    If you find this useful, don’t forget to like and share~

    Leave a Comment