深入解析:Win+VsCode关于C++项目改造成http服务
2025-11-26 16:23 tlnshuju 阅读(7) 评论(0) 收藏 举报具体的MSYS2及vscode关于C++任务的调整,参考上一篇博客:
https://blog.csdn.net/weixin_41212298/article/details/154026060
本工程是在windows系统上进行设置的。
1.基本的 C++ 项目结构
my_project/ ├── bin/ ├── src/ │ └── main.cpp ├── include/ ├── .vscode/ │ ├── tasks.json │ ├── launch.json │ └── c_cpp_properties.json └── Makefile (或 CMakeLists.txt) |
如:

2.编写示例代码
由于本人启用的windows环境,因此采用纯净版服务
2.1 src/main.cpp:
#define _WIN32_WINNT 0x0A00 #define WIN32_LEAN_AND_MEAN #include <iostream> #include <vector> #include <thread> #include <mutex> #include <map> #include <string> #include <sstream> #include <winsock2.h> #include <ws2tcpip.h> #pragma comment(lib, "ws2_32.lib") using namespace std; class MathService { public: static int add(int a, int b) { return a + b; } static int multiply(int a, int b) { return a * b; } static vector<int> fibonacci(int n) { vector<int> result; if (n <= 0) return result; result.push_back(0); if (n == 1) return result; result.push_back(1); for (int i = 2; i < n; i++) { result.push_back(result[i-1] + result[i-2]); } return result; } }; string create_response(const string& content, const string& content_type = "application/json") { stringstream response; response << "HTTP/1.1 200 OK\r\n" << "Content-Type: " << content_type << "\r\n" << "Content-Length: " << content.length() << "\r\n" << "Connection: close\r\n" << "Access-Control-Allow-Origin: *\r\n" << "\r\n" << content; return response.str(); } string handle_request(const string& request) { if (request.find("GET /health") != string::npos) { return create_response(R"({"status": "healthy", "service": "Windows Socket Server"})"); } else if (request.find("GET /api/add") != string::npos) { int a = 15, b = 25; int result = MathService::add(a, b); return create_response(R"({"operation": "add", "a": )" + to_string(a) + R"(, "b": )" + to_string(b) + R"(, "result": )" + to_string(result) + "}"); } else if (request.find("GET /api/multiply") != string::npos) { int a = 8, b = 7; int result = MathService::multiply(a, b); return create_response(R"({"operation": "multiply", "a": )" + to_string(a) + R"(, "b": )" + to_string(b) + |
浙公网安备 33010602011771号