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

C++ Web服务器无法正确返回数据,Chrome提示HTTP响应错误

Fixing the HTTP Response Error in Your Minimal Windows Web Server

Ah, I see the issue here! Chrome is throwing an HTTP response error because your server isn't sending a valid HTTP response—browsers expect communication to follow the HTTP protocol rules, and right now you're just sending a raw string without the required headers.

Why This Happens

Web browsers (like Chrome) communicate using the HTTP protocol, which requires a specific structure for responses. Your current code sends only "Hello Web\r\n", which lacks the mandatory status line and headers that the browser needs to interpret the response correctly.

A Minimal Valid HTTP Response Structure

A working minimal HTTP response looks like this:

HTTP/1.1 200 OK\r\n
Content-Type: text/plain\r\n
Content-Length: 9\r\n
\r\n
Hello Web

Breaking this down:

  • HTTP/1.1 200 OK: Status line declaring the HTTP version and success status
  • Content-Type: text/plain: Tells the browser the body is plain text
  • Content-Length: 9: Specifies the length of the response body (9 characters for "Hello Web")
  • The blank line (\r\n) separates headers from the body
  • The final line is your actual response text

Corrected Server Code

Here's your updated code that sends a proper HTTP response, plus some basic error checking and cleanup:

#include <iostream>
#include <winsock2.h>
#include <string>
using namespace std;

int main() {
    WSADATA WSAData;
    SOCKET server, client;
    SOCKADDR_IN serverAddr, clientAddr;

    // Initialize Winsock with error checking
    if (WSAStartup(MAKEWORD(2,0), &WSAData) != 0) {
        cerr << "Winsock initialization failed!" << endl;
        return 1;
    }

    // Create socket with error checking
    server = socket(AF_INET, SOCK_STREAM, 0);
    if (server == INVALID_SOCKET) {
        cerr << "Socket creation failed! Error: " << WSAGetLastError() << endl;
        WSACleanup();
        return 1;
    }

    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(5555);

    // Bind socket with error checking
    if (bind(server, (SOCKADDR *)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
        cerr << "Bind failed! Error: " << WSAGetLastError() << endl;
        closesocket(server);
        WSACleanup();
        return 1;
    }

    // Listen for connections with error checking
    if (listen(server, 0) == SOCKET_ERROR) {
        cerr << "Listen failed! Error: " << WSAGetLastError() << endl;
        closesocket(server);
        WSACleanup();
        return 1;
    }

    cout << "Listening for incoming connections on 127.0.0.1:5555..." << endl;

    char buffer[1024];
    int clientAddrSize = sizeof(clientAddr);

    if((client = accept(server, (SOCKADDR *)&clientAddr, &clientAddrSize)) != INVALID_SOCKET) {
        cout << "Client connected!" << endl;
        
        // Read client request (we don't need to parse it for this minimal server)
        recv(client, buffer, sizeof(buffer), 0);
        cout << "Received client request snippet: " << string(buffer).substr(0, 50) << "..." << endl;

        // Construct valid HTTP response
        string response = 
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/plain\r\n"
            "Content-Length: 9\r\n"
            "\r\n"
            "Hello Web";

        // Send the response
        send(client, response.c_str(), response.size(), 0);
        cout << "Sent response: \n" << response << endl;

        memset(buffer, 0, sizeof(buffer));
        closesocket(client);
        cout << "Client disconnected." << endl;
    }

    // Clean up Winsock resources
    closesocket(server);
    WSACleanup();
    return 0;
}

Key Changes Made

  • Valid HTTP Response: Updated the response string to include all required HTTP components so Chrome can properly interpret it
  • Error Checking: Added checks for Winsock initialization, socket creation, bind, and listen operations to help diagnose issues
  • Proper Cleanup: Added closesocket(server) and WSACleanup() to properly release Winsock resources when done
  • Request Handling: Added a snippet of the client request to help with debugging (you can remove this if not needed)

Now when you run this code and visit 127.0.0.1:5555 in Chrome, you'll see "Hello Web" displayed correctly without any HTTP errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:46:21