• Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)


    场景

    SpringBoot+Vue整合WebSocket实现前后端消息推送:

    SpringBoot+Vue整合WebSocket实现前后端消息推送_霸道流氓气质的博客-CSDN博客

    在上面集成Websocket实现消息推送的基础上。

    除给web端页面进行推送数据,还需要给Android端推送数据。

    在特殊的业务场景下,Android会经常性断网和关机,SpringBoot后台jar包部署在Windows服务器上。

    当终端过多且累计一段时间后,因频繁断网和关机导致的与后台jar包tcp连接数不会关闭,

    当超过最大连接数时(8000),则该服务会提示拒绝连接。

    Windows上查看连接数除了使用命令之外,还可以借助于其它第三方工具比如Cports端口扫描工具等。

     

    在jar包所在服务上运行exe,如果该服务器上还有其他端口服务存在,可进行筛选指定端口的连接

     

    比如只筛选7777端口,在筛选器中输入

    include:both:tcp:7777

     

    注:

    博客:
    https://blog.csdn.net/badao_liumang_qizhi 
    关注公众号
    霸道的程序猿
    获取编程相关电子书、教程推送与免费下载。

    实现

    1、用Android模拟器以及websocket测试软件来模拟上面异常关闭连接(断网)连接数不变的情况

    首先建立起多个连接,可以看到连接数会增多。

    然后将APP的网络突然断掉,此时可以看到连接数并不会被关掉

     

    当网络再次恢复时,连接数会持续增多

     

    此时可以通过cports工具选中连接数并关闭

    或者直接重启后台jar包,则连接会断开

     

    2、Nginx配置Websocket代理

    可以参考官网文档

    WebSocket proxying

    To turn a connection between a client and server from HTTP/1.1 into WebSocket, the protocol switch mechanism available in HTTP/1.1 is used.

    There is one subtlety however: since the “Upgrade” is a hop-by-hop header, it is not passed from a client to proxied server. With forward proxying, clients may use the CONNECT method to circumvent this issue. This does not work with reverse proxying however, since clients are not aware of any proxy servers, and special processing on a proxy server is required.

    Since version 1.3.13, nginx implements special mode of operation that allows setting up a tunnel between a client and proxied server if the proxied server returned a response with the code 101 (Switching Protocols), and the client asked for a protocol switch via the “Upgrade” header in a request.

    As noted above, hop-by-hop headers including “Upgrade” and “Connection” are not passed from a client to proxied server, therefore in order for the proxied server to know about the client’s intention to switch a protocol to WebSocket, these headers have to be passed explicitly:

    1. location /chat/ {
    2.     proxy_pass http://backend;
    3.     proxy_http_version 1.1;
    4.     proxy_set_header Upgrade $http_upgrade;
    5.     proxy_set_header Connection "upgrade";
    6. }


    A more sophisticated example in which a value of the “Connection” header field in a request to the proxied server depends on the presence of the “Upgrade” field in the client request header:

    1. http {
    2.     map $http_upgrade $connection_upgrade {
    3.         default upgrade;
    4.         ''      close;
    5.     }
    6.     server {
    7.         ...
    8.         location /chat/ {
    9.             proxy_pass http://backend;
    10.             proxy_http_version 1.1;
    11.             proxy_set_header Upgrade $http_upgrade;
    12.             proxy_set_header Connection $connection_upgrade;
    13.         }
    14.     }


    By default, the connection will be closed if the proxied server does not transmit any data within 60 seconds. This timeout can be increased with the proxy_read_timeout directive. Alternatively, the proxied server can be configured to periodically send WebSocket ping frames to reset the timeout and check if the connection is still alive.

    3、按照官方文档的示例和说明修改nginx的配置文件

    按照示例配置,首先需要配置一个上游服务器upstream,示例配置中叫backend,这里叫websocket

    1.  upstream websocket {
    2.   server 10.229.36.139:7777;
    3.  }

    添加位置

    这里的server指定的是原来的ip和端口。

    然后按照示例代码添加其他配置

    1.  map $http_upgrade $connection_upgrade {
    2.         default upgrade;
    3.         ''      close;
    4.     }
    5.  
    6.     #gzip  on;
    7.  upstream websocket {
    8.   server 10.229.36.139:7777;
    9.  }
    10.  
    11.     server {
    12.         listen       88;
    13.         server_name  localhost;
    14.         #charset koi8-r;
    15.         #access_log  logs/host.access.log  main;
    16.         location / {
    17.             root   html;
    18.             index  index.html index.htm;
    19.         }
    20.   
    21.   location /websocket/ {
    22.             proxy_pass http://websocket;
    23.             proxy_http_version 1.1;
    24.    proxy_read_timeout 10s;
    25.    proxy_send_timeout 10s;
    26.             proxy_set_header Upgrade $http_upgrade;
    27.             proxy_set_header Connection $connection_upgrade;
    28.         }

    主要添加这两块

     

    与示例代码不同的是,这里还按照官方说明添加了超时的时间设置,这里为10s,意思就是说十秒之内没有任何通讯和消息传输就会关闭该连接。

     

    完整nginx.conf配置文件

    1. #user  nobody;
    2. worker_processes  1;
    3. #error_log  logs/error.log;
    4. #error_log  logs/error.log  notice;
    5. #error_log  logs/error.log  info;
    6. #pid        logs/nginx.pid;
    7. events {
    8.     worker_connections  1024;
    9. }
    10. http {
    11.     include       mime.types;
    12.     default_type  application/octet-stream;
    13.     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    14.     #                  '$status $body_bytes_sent "$http_referer" '
    15.     #                  '"$http_user_agent" "$http_x_forwarded_for"';
    16.     #access_log  logs/access.log  main;
    17.     sendfile        on;
    18.     #tcp_nopush     on;
    19.     #keepalive_timeout  0;
    20.     keepalive_timeout  65;
    21.  map $http_upgrade $connection_upgrade {
    22.         default upgrade;
    23.         ''      close;
    24.     }
    25.  
    26.     #gzip  on;
    27.  upstream websocket {
    28.   server 10.229.36.139:7777;
    29.  }
    30.  
    31.     server {
    32.         listen       88;
    33.         server_name  localhost;
    34.         #charset koi8-r;
    35.         #access_log  logs/host.access.log  main;
    36.         location / {
    37.             root   html;
    38.             index  index.html index.htm;
    39.         }
    40.   
    41.   location /websocket/ {
    42.             proxy_pass http://websocket;
    43.             proxy_http_version 1.1;
    44.    proxy_read_timeout 10s;
    45.    proxy_send_timeout 10s;
    46.             proxy_set_header Upgrade $http_upgrade;
    47.             proxy_set_header Connection $connection_upgrade;
    48.         }
    49.         #error_page  404              /404.html;
    50.         # redirect server error pages to the static page /50x.html
    51.         #
    52.         error_page   500 502 503 504  /50x.html;
    53.         location = /50x.html {
    54.             root   html;
    55.         }
    56.         # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    57.         #
    58.         #location ~ \.php$ {
    59.         #    proxy_pass   http://127.0.0.1;
    60.         #}
    61.         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    62.         #
    63.         #location ~ \.php$ {
    64.         #    root           html;
    65.         #    fastcgi_pass   127.0.0.1:9000;
    66.         #    fastcgi_index  index.php;
    67.         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    68.         #    include        fastcgi_params;
    69.         #}
    70.         # deny access to .htaccess files, if Apache's document root
    71.         # concurs with nginx's one
    72.         #
    73.         #location ~ /\.ht {
    74.         #    deny  all;
    75.         #}
    76.     }
    77.     # another virtual host using mix of IP-, name-, and port-based configuration
    78.     #
    79.     #server {
    80.     #    listen       8000;
    81.     #    listen       somename:8080;
    82.     #    server_name  somename  alias  another.alias;
    83.     #    location / {
    84.     #        root   html;
    85.     #        index  index.html index.htm;
    86.     #    }
    87.     #}
    88.     # HTTPS server
    89.     #
    90.     #server {
    91.     #    listen       443 ssl;
    92.     #    server_name  localhost;
    93.     #    ssl_certificate      cert.pem;
    94.     #    ssl_certificate_key  cert.key;
    95.     #    ssl_session_cache    shared:SSL:1m;
    96.     #    ssl_session_timeout  5m;
    97.     #    ssl_ciphers  HIGH:!aNULL:!MD5;
    98.     #    ssl_prefer_server_ciphers  on;
    99.     #    location / {
    100.     #        root   html;
    101.     #        index  index.html index.htm;
    102.     #    }
    103.     #}
    104. }

    4、配置之后启动Nginx

    此时websocket可以通过代理的88端口进行连接

    并且在不断网情况下,超过10秒没有消息就会关闭连接。

     异常断网的情况也是如此

     

  • 相关阅读:
    GBase 8c V3.0.0数据类型——范围函数
    从源码上看,RocketMQ 5.0 跟 RocketMQ 4.x相比增加了哪几个模块
    HarmonyOS NEXT应用开发案例——自定义TabBar
    在 Vue 应用中下载.doc文档(或任何其他类型的文件)
    深入浅出 Spring Boot 多种设定档管里(Spring Profiles)
    HR350学习笔记(一)概览
    SpringBoot发送邮件(SpringBoot整合JavaMail)
    Python 之plt.plot()的介绍以及使用
    注册表单mvc 含源代码
    63.【c++基础篇.三个文件实现】
  • 原文地址:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/126082838