丝甲坞 发表于 2025-6-4 20:03:57

⑨也能看懂的 nginx 与 C++ 简易版集成

原理概述

nginx 运行在端口A,转发数据给端口B,C++ 监听端口B的数据。
本文例子

使用 C++ 和 nginx 获取客户端的IP地址
代码

nginx 配置

#usernobody;
worker_processes1;

events {
    worker_connections1024;
}

http {
    include       mime.types;
    default_typeapplication/octet-stream;

    sendfile      on;

    keepalive_timeout65;

    server {
      listen       2335;
      # 如果用服务器启动nginx, 这里写服务器的地址, 不写 localhost
      # 例如: server_name1xx.1xx.1xx.1xx
      server_namelocalhost;

      # 转发 API 请求到 C++ 应用
      location / {
      # 假设 C++ 应用运行在 5033 端口
      proxy_pass http://localhost:5033/;
      # 使用 HTTP/1.1
      proxy_http_version 1.1;
      # 支持 WebSocket
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }

      error_page   500 502 503 504/50x.html;
      location = /50x.html {
            root   html;
      }

    }

}CPP代码

#include #include #include #pragma comment(lib, "ws2_32.lib")using std::cout;using std::endl;using std::string;int main(){    WSADATA wsa;    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)    {      cout
页: [1]
查看完整版本: ⑨也能看懂的 nginx 与 C++ 简易版集成