You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python WebSocket服务器与C++客户端通信:消息无法接收问题

Python WebSocket服务器与C++客户端通信故障排查

C客户端可正常连接Python WebSocket服务器,但发送的消息始终无法被服务器接收。客户端无报错且显示消息发送成功,未出现异常结果。使用命令python -m websockets ws://localhost:3000/可正常与服务器通信,推测问题出在C端,但对照教程未发现差异,需排查原因。

C++客户端代码

#include <winsock2.h>
#include <ws2tcpip.h>
#include "iostream"
#include <tchar.h>
#define IP "127.0.0.1"
constexpr int PORT = 3000;
int main() {
    std::cout << "======== CC Client ========" << std::endl;

    std::cout << "==== Invoke WSAStartup ====" << std::endl;
    SOCKET clientSocket;
    WSADATA wsaData;
    int wsaerr;
    WORD wVersionRequested = MAKEWORD(2, 2);
    wsaerr = WSAStartup(wVersionRequested, &wsaData);
    if (wsaerr == 0) {
        std::cout << "Winsock dll found!" << std::endl;
        std::cout << "Status: " << wsaData.szSystemStatus << std::endl;
    }
    else {
        std::cout << "Winsock dll not found." << std::endl;
        return 0;
    }

    std::cout << "===== Creating Socket =====" << std::endl;
    clientSocket = INVALID_SOCKET;
    clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (clientSocket != INVALID_SOCKET) 
        std::cout << "socket() is OK!" << std::endl;
    else {
        std::cout << "Error at socket():" << WSAGetLastError() << std::endl;
        WSACleanup();
        return 0;
    }
    
    std::cout << "==== Connect to Server ====" << std::endl;
    sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    InetPton(AF_INET,_T(IP), &clientService.sin_addr.s_addr);
    clientService.sin_port = htons(PORT);
    if (connect(clientSocket, (SOCKADDR*)&clientService, sizeof(clientService)) != SOCKET_ERROR) {
        std::cout << "Client: connect() is OK." << std::endl;
        std::cout << "Connected to: " << IP << ":" << PORT << std::endl;
        std::cout << "Client: Can start sending and receiving data..." << std::endl;
    }
    else {
        std::cout << "Client: connect() - Failed to connect." << std::endl;
        WSACleanup();
        return 0;
    }

    std::cout << "== Communicate to Server ==" << std::endl;
    
    char buffer[200];
    std::cout << "Enter a message:" << std::endl;
    std::cin.getline(buffer, 200);
    int byteCount = send(clientSocket, buffer, 200, 0);
    if (byteCount > 0)
        std::cout << "Message sent: " << buffer << std::endl;
    else {
        std::cout << "Message failed to send." << std::endl;
        WSACleanup();
    }

    std::cout << "===== Clean up Socket =====" << std::endl;
    system("pause");
    WSACleanup();
}

Python服务器代码

import asyncio
import websockets


async def handler(websocket):
    while True:
        try:
            message = await websocket.recv()
            print(message)
        except websockets.ConnectionClosedOK:
            break
        except websockets.exceptions.ConnectionClosed:
            print("A client suddenly disconnected.")


async def main():
    async with websockets.serve(handler, "localhost", 3000):
        await asyncio.Future()  # run forever

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

内容的提问来源于stack exchange,提问作者massacring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 20:55:15