C++ windows HTTP 服务器demo

C++ windows HTTP 服务器 ,用来验证MES的post get

cpp 复制代码
#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>

// 引入静态链接库
#pragma comment(lib, "ws2_32.lib")

const int DEFAULT_PORT = 8889;

// 处理GET请求的函数,这里简单返回固定内容示例
std::string handleGetRequest(const std::string& request) {
    std::string response = "HTTP/1.1 200 OK\r\n";
    response += "Content-Type: text/html; charset=UTF-8\r\n";
    response += "\r\n";
    response += "<html><body><h1>Hello from GET!</h1></body></html>";
    return response;
}

// 处理POST请求的函数,这里简单返回固定内容示例,实际中可根据POST数据做处理
std::string handlePostRequest(const std::string& request) {
    std::string response = "HTTP/1.1 200 OK\r\n";
    response += "Content-Type: text/html; charset=UTF-8\r\n";
    response += "\r\n";
    response += "<html><body><h1>Hello from POST!</h1></body></html>";
    return response;
}

int main() {
    // 初始化WinSock
    WSADATA wsaData;
    int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (result != 0) {
        std::cerr << "WSAStartup failed: " << result << std::endl;
        return 1;
    }

    // 创建套接字
    SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSocket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed: " << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 绑定地址和端口
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(DEFAULT_PORT);
    result = bind(listenSocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
    if (result == SOCKET_ERROR) {
        std::cerr << "Bind failed: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    // 监听端口
    result = listen(listenSocket, SOMAXCONN);
    if (result == SOCKET_ERROR) {
        std::cerr << "Listen failed: " << WSAGetLastError() << std::endl;
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    std::cout << "Server is listening on port " << DEFAULT_PORT << std::endl;

    while (true) {
        // 接受客户端连接
        SOCKET clientSocket = accept(listenSocket, NULL, NULL);
        if (clientSocket == INVALID_SOCKET) {
            std::cerr << "Accept failed: " << WSAGetLastError() << std::endl;
            continue;
        }

        char buffer[1024];
        int bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
        if (bytesReceived > 0) {
            buffer[bytesReceived] = '\0';
            std::string request(buffer);
            std::string response;

            // 判断请求方法是GET还是POST
            if (request.find("GET") == 0) {
                response = handleGetRequest(request);
            }
            else if (request.find("POST") == 0) {
                response = handlePostRequest(request);
            }
            else {
                // 对于不支持的方法返回405 Method Not Allowed
                response = "HTTP/1.1 405 Method Not Allowed\r\n";
                response += "Content-Type: text/html; charset=UTF-8\r\n";
                response += "\r\n";
                response += "<html><body><h1>405 Method Not Allowed</h1></body></html>";
            }

            // 发送响应给客户端
            send(clientSocket, response.c_str(), response.length(), 0);
        }

        // 关闭客户端套接字
        closesocket(clientSocket);
    }

    // 关闭监听套接字,清理WinSock环境
    closesocket(listenSocket);
    WSACleanup();
    return 0;
}
相关推荐
岳轩子38 分钟前
23种设计模式之备忘录模式
windows·设计模式·备忘录模式
汝即来归43 分钟前
什么是运算符重载?如何在 C++ 中进行运算符重载?运算符重载在面向对象编程中的好处是什么?
开发语言·c++
IT信息技术学习圈1 小时前
2024年12月CCF编程能力等级认证(GESP)C++一级试卷讲解
开发语言·c++
liupenglove1 小时前
protobuf c++开发快速上手指南
开发语言·c++
丁劲犇1 小时前
让 Win10 上网本 Debug 模式 QUDPSocket 信号&槽 收发不丢包的方法总结
网络·windows·qt·网络协议·udp·qudpsocket·丢包
卜及中2 小时前
【数据结构】B树家族解析:B树、B+树与B*树的理论与B树插入实现(C++)
开发语言·数据结构·c++·b树
m0_748247803 小时前
如何使用Node.js快速创建本地HTTP服务器并实现异地远程访问
服务器·http·node.js
PluviophileDD4 小时前
【笔记】C语言转C++
c语言·c++
獨枭4 小时前
MFC 自定义编辑框:打造灵活的数据输入控件
c++·mfc
逆袭之路6665 小时前
浅谈右值引用 移动语义 完美转发 std::move std::forward,窥探模板元编程的一角
c++