在本實驗中,我們將在 Windows 系統 上使用 Python 編寫一個 TCP 服務器,并啟動兩個服務實例。然后使用 Nginx 或 HAProxy 作為負載均衡器,將來自多個客戶端的請求分發到這兩個服務實例上,驗證負載均衡效果。
🧩 環境準備
- 操作系統:Windows 10 / Windows 11
- Python 3.x(建議使用 Python 3.10+)
- Nginx for Windows 或 HAProxy for Windows
- 10 個客戶端(使用 Python 編寫)
一、Python TCP 服務器代碼
📁 server.py
import socketdef start_server(port):server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server_socket.bind(('0.0.0.0', port))server_socket.listen(5)print(f"Server started on port {port}")while True:client_socket, addr = server_socket.accept()print(f"Connection from {addr}")data = client_socket.recv(1024)print(f"Received: {data.decode()}")response = f"Response from server on port {port}\n"client_socket.sendall(response.encode())client_socket.close()if __name__ == "__main__":import sysif len(sys.argv) != 2:print("Usage: python server.py <port>")sys.exit(1)port = int(sys.argv[1])start_server(port)
🔧 啟動兩個服務實例
打開兩個命令行窗口,分別運行:
# 第一個服務實例
python server.py 8000# 第二個服務實例
python server.py 8001
二、使用 Nginx 做 TCP 負載均衡(Windows 版本)
Nginx Windows 版本默認 不包含 stream 模塊,所以需要使用 第三方模塊 或使用 WSL(推薦使用 WSL)。不過我們這里使用 Nginx for Windows 的 stream 模塊支持版本。
1. 下載并安裝 Nginx for Windows(含 stream 模塊)
推薦使用 Nginx + stream module for Windows 或使用 XAMPP 中的 Nginx。
下載后解壓到目錄,例如:C:\nginx
2. 配置 Nginx TCP 負載均衡
編輯 C:\nginx\conf\nginx.conf
,在文件末尾添加:
stream {upstream tcp_backend {least_conn;server 127.0.0.1:8000;server 127.0.0.1:8001;}server {listen 9000;proxy_pass tcp_backend;}
}
3. 啟動 Nginx
在命令行中進入 Nginx 目錄并啟動:
cd C:\nginx
start nginx
檢查是否啟動成功:
nginx -t
如果配置正確,不會報錯。
三、使用 HAProxy 做 TCP 負載均衡(Windows 版本)
1. 下載并安裝 HAProxy for Windows
前往 HAProxy 官方下載頁面 或使用 HAProxy for Windows。
解壓后放到 C:\haproxy
。
2. 配置 HAProxy
創建配置文件 C:\haproxy\haproxy.cfg
:
globallog 127.0.0.1 local0log 127.0.0.1 local1 noticechroot C:/haproxystats socket ipv4@127.0.0.1:9999 level adminstats timeout 30suser haproxygroup haproxydaemondefaultslog globalmode tcpoption tcplogtimeout connect 5000mstimeout client 60000mstimeout server 60000msfrontend tcp_frontbind *:9000default_backend tcp_backbackend tcp_backbalance leastconnserver server1 127.0.0.1:8000 checkserver server2 127.0.0.1:8001 check
3. 啟動 HAProxy
打開命令行,進入 HAProxy 目錄并運行:
cd C:\haproxy
haproxy.exe -f haproxy.cfg
四、編寫客戶端測試負載均衡效果(Windows)
📁 client.py
import socket
import sys
import threadingdef send_request(client_id):client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client_socket.connect(('127.0.0.1', 9000))message = f"Hello from client {client_id}"client_socket.sendall(message.encode())response = client_socket.recv(1024).decode()print(f"Client {client_id} received: {response}")client_socket.close()if __name__ == "__main__":threads = []for i in range(1, 11): # 啟動10個客戶端t = threading.Thread(target=send_request, args=(i,))threads.append(t)t.start()for t in threads:t.join()
🚀 運行客戶端測試
python client.py
五、查看服務器日志確認負載均衡效果
運行兩個服務端(8000 和 8001),觀察它們的輸出日志,確認請求是否被交替分配。
示例輸出(server.py):
Connection from ('127.0.0.1', 54321)
Received: Hello from client 1
Connection from ('127.0.0.1', 54322)
Received: Hello from client 2
如果兩個服務端交替收到請求,說明負載均衡生效。
六、常見問題與注意事項(Windows)
問題 | 解決方法 |
---|---|
bind: permission denied | 使用管理員權限運行 CMD |
socket.error: [WinError 10048] | 確保端口未被占用 |
Nginx 啟動失敗 | 檢查 nginx.conf 是否語法正確,關閉占用 80/9000 端口的程序 |
HAProxy 啟動失敗 | 檢查配置文件路徑、端口是否被占用 |
Windows 防火墻攔截 | 添加 Nginx/HAProxy 為允許通過防火墻的程序 |
七、總結
工具 | 協議支持 | 負載均衡算法 | Windows 支持 | 優點 |
---|---|---|---|---|
Nginx | TCP(需 stream 模塊) | least_conn, round-robin | 有限(推薦使用 WSL) | 易于配置,適合 HTTP/TCP 混合場景 |
HAProxy | TCP | least_conn, round-robin, uri 等 | 支持(需下載 Windows 版本) | 專業 TCP 負載均衡器,功能豐富 |
有興趣的還可以繼續實現 HTTPS、限流、健康檢查等功能!