这个项目演示了如何使用 C++和 Python 实现 WebSocket 通信。包含完整的客户端和服务器实现,支持 Windows、Linux 和 macOS。
.
├── python_server.py # Python WebSocket服务器
├── python_client.py # Python WebSocket客户端
├── cpp_server.cpp # C++ WebSocket服务器
├── cpp_client.cpp # C++ WebSocket客户端
├── CMakeLists.txt # C++项目构建配置
├── requirements.txt # Python依赖
└── README.md # 本文件
- Python 3.7+
- websockets 库
- C++17 编译器(GCC 7+, Clang 6+, MSVC 2017+)
- Boost 库 1.70+(需要 system 和 json 组件)
- CMake 3.10+
pip install -r requirements.txt
# 使用vcpkg安装Boost
vcpkg install boost-beast:x64-windows boost-json:x64-windows
sudo apt-get update
sudo apt-get install libboost-all-dev cmake g++
brew install boost cmake
# 创建构建目录
mkdir build
cd build
# 配置项目
cmake ..
# 编译
cmake --build .
# 编译后的可执行文件在build目录下
# 编译客户端
g++ -std=c++17 cpp_client.cpp -o cpp_client -lboost_system -lpthread
# 编译服务器
g++ -std=c++17 cpp_server.cpp -o cpp_server -lboost_system -lpthread
cl /EHsc /std:c++17 cpp_client.cpp /link boost_system.lib
cl /EHsc /std:c++17 cpp_server.cpp /link boost_system.lib
终端 1 - 启动 Python 服务器:
python python_server.py
终端 2 - 启动 C++客户端:
# Linux/macOS
./build/cpp_client localhost 8765
# Windows
build\Debug\cpp_client.exe localhost 8765
终端 1 - 启动 C++服务器:
# Linux/macOS
./build/cpp_server 8766
# Windows
build\Debug\cpp_server.exe 8766
终端 2 - 启动 Python 客户端:
python python_client.py ws://localhost:8766
你可以同时运行多个客户端(Python 或 C++),它们都能相互通信:
终端 1 - Python 服务器:
python python_server.py
终端 2 - C++客户端 1:
./build/cpp_client
终端 3 - Python 客户端:
python python_client.py
终端 4 - C++客户端 2:
./build/cpp_client
所有消息使用 JSON 格式:
{
"type": "message",
"message": "你的消息内容",
"timestamp": "2025-10-03T12:00:00Z",
"from": "Python客户端" 或 "C++ Client"
}
{
"type": "welcome",
"message": "欢迎连接到WebSocket服务器!",
"timestamp": "2025-10-03T12:00:00Z"
}
{
"type": "response",
"original_message": {...},
"echo": "服务器收到: 你的消息",
"timestamp": "2025-10-03T12:00:00Z"
}
{
"type": "broadcast",
"from": "客户端地址",
"message": "广播的消息内容",
"timestamp": "2025-10-03T12:00:00Z"
}
- ✅ 跨平台支持(Windows、Linux、macOS)
- ✅ Python 和 C++互操作
- ✅ JSON 消息格式
- ✅ 多客户端支持
- ✅ 消息广播功能
- ✅ 时间戳记录
- ✅ 异步 I/O
- ✅ 自动重连支持(可扩展)
-
启动服务器
python python_server.py
-
启动 C++客户端
./build/cpp_client
-
发送消息
- 在客户端输入任意文本并按回车
- 服务器会回显消息
- 其他客户端会收到广播
-
测试跨语言通信
- 同时运行 Python 客户端和 C++客户端
- 验证它们能相互接收消息
# Linux: 设置Boost路径
export BOOST_ROOT=/path/to/boost
# Windows: 在CMake中指定
cmake -DBOOST_ROOT=C:\path\to\boost ..
# 更改服务器端口
python python_server.py # 修改代码中的端口号
./cpp_server 9000 # 使用不同端口
- 确保服务器已启动
- 检查防火墙设置
- 验证 IP 地址和端口正确
- 添加认证机制 - 实现用户登录验证
- 消息加密 - 使用 SSL/TLS 加密 WebSocket 连接
- 持久化 - 将消息保存到数据库
- Web 界面 - 添加浏览器端 WebSocket 客户端
- 重连机制 - 实现自动重连功能
- 心跳检测 - 添加连接健康检查
本项目仅供学习和参考使用。
欢迎提交问题和改进建议!
祝你使用愉快! 🎉