丝甲坞 发表于 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

猷浮 发表于 2025-11-27 01:24:39

过来提前占个楼

韶侪 发表于 2025-12-27 16:28:02

谢谢分享,试用一下

劝匠注 发表于 2026-1-14 09:34:57

热心回复!

贺蛟亡 发表于 2026-1-18 05:54:10

谢谢楼主提供!

闻成 发表于 2026-1-22 13:02:04

谢谢分享,试用一下

全愉婉 发表于 2026-1-23 06:19:53

谢谢分享,试用一下

柴古香 发表于 2026-1-23 09:37:24

前排留名,哈哈哈

俏襟选 发表于 2026-1-26 12:39:22

谢谢楼主提供!

史华乐 发表于 4 天前

yyds。多谢分享

赏勿 发表于 16 小时前

东西不错很实用谢谢分享

钦娅芬 发表于 16 小时前

yyds。多谢分享

饨篦 发表于 8 小时前

新版吗?好像是停更了吧。
页: [1]
查看完整版本: ⑨也能看懂的 nginx 与 C++ 简易版集成