什么是websocket

WebSocket是一种网络通信协议,旨在为客户端和服务器之间提供全双工(full-duplex)通信。与传统的HTTP通信不同,WebSocket允许在单个连接上进行双向数据传输,适用于实时应用程序。

HTTP vs Websocket

  • http 协议请求流程(简图)
    http协议流程简图
  • websocket 协议请求流程(简图)
    websocket协议流程简图

配置要点

  1. websocket开始连接的时候,客户端会给服务器发起一个HTTP请求,请求头中包含Upgrade:websocketconnection:Upgradenginx需要把请求头中的这些信息转发给后端的websocket服务。
  2. websocket需要使用http/1.1协议,所以需要在配置中指定proxy_http_version 1.1
  3. 如上图所示,websocket是长连接,所以需要在配置中设置一个timeout,避免连接被nginx自动关闭。

配置websocket

当需要通过nginx反代websocket服务时,我们需要在nginx配置中做一些修改,因为nginx默认是不支持websokcet协议的。

  1. 常规配置
server {
    listen 80;
    server_name xp.sb;
    
    location /ws/ {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400s; # 24 hours
        proxy_send_timeout 86400s; # 24 hours}

    }
}
  1. 负载均衡
upstream ws_backend {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080;
}

server {
    listen 80;
    server_name xp.sb;
    
    location /ws/ {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400s; # 24 hours
        proxy_send_timeout 86400s; # 24 hours}

        # 确保客户端始终连接到同一个后端服务器
        ip_hash;
    }
}
  1. 连接数限制
localtion /ws/ {
    ....
    # 每个ip最多保持10个ws连接
    limit_conn conn_per_ip 10;
}

# http 块中定义连接限制区
http {
   ...
   limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m
  ...
}
  1. 缓冲区配置
    location /ws/ {
        ...
        proxy_buffer_size 16k;
        proxy_buffer 4 32k;
        proxy_busy_buffers_size 64;
    }
  1. 心跳检测配置
    location /ws/ {
        ...
        proxy_websocket_keepalive_timeout 20;
        proxy_websocket_keepalive_interval 5;
    }
  1. SSL配置

    server {
     listen 443 ssl;
     http2 on;
     server_name xp.sb;
     
     ssl_certificate /usr/local/nginx/conf/ssl/xp.sb/fullchain.cer;
     ssl_certificate_key /usr/local/nginx/conf/ssl/xp.sb/xp.sb.key;
     location /ws/ {
         proxy_pass http://websocket_backend;
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection "upgrade";
         proxy_read_timeout 86400s; # 24 hours
         proxy_send_timeout 86400s; # 24 hours}
     }
    }

标签: nginx, http, websocket

添加新评论