找回密码
 立即注册
首页 资源区 代码 ⑨也能看懂的 nginx 与 C++ 简易版集成

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

丝甲坞 2025-6-4 20:03:57
原理概述

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

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

nginx 配置
  1. #user  nobody;
  2. worker_processes  1;
  3. events {
  4.     worker_connections  1024;
  5. }
  6. http {
  7.     include       mime.types;
  8.     default_type  application/octet-stream;
  9.     sendfile        on;
  10.     keepalive_timeout  65;
  11.     server {
  12.         listen       2335;
  13.         # 如果用服务器启动nginx, 这里写服务器的地址, 不写 localhost
  14.         # 例如: server_name  1xx.1xx.1xx.1xx
  15.         server_name  localhost;
  16.         # 转发 API 请求到 C++ 应用
  17.         location / {
  18.         # 假设 C++ 应用运行在 5033 端口
  19.         proxy_pass http://localhost:5033/;
  20.         # 使用 HTTP/1.1
  21.         proxy_http_version 1.1;
  22.         # 支持 WebSocket
  23.         proxy_set_header Upgrade $http_upgrade;
  24.         proxy_set_header Connection 'upgrade';
  25.         proxy_set_header Host $host;
  26.         proxy_cache_bypass $http_upgrade;
  27.         proxy_set_header X-Real-IP $remote_addr;
  28.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  29.         }
  30.         error_page   500 502 503 504  /50x.html;
  31.         location = /50x.html {
  32.             root   html;
  33.         }
  34.     }
  35. }
复制代码
CPP代码

[code]#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
您需要登录后才可以回帖 登录 | 立即注册