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

场景

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

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/114392573

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

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

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

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

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

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

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

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

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

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

include:both:tcp:7777

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

注:

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

实现

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

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

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

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

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

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

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

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

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

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

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

2、Nginx配置Websocket代理

可以参考官网文档

http://nginx.org/en/docs/http/websocket.html

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:

location /chat/ {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

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:

http {
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    server {
        ...

        location /chat/ {
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }
    }

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

upstream websocket {
  server 10.229.36.139:7777;
 }

添加位置

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

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

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

map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    #gzip  on;

 upstream websocket {
  server 10.229.36.139:7777;
 }

    server {
        listen       88;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

  location /websocket/ {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
   proxy_read_timeout 10s;
   proxy_send_timeout 10s;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }

主要添加这两块

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

与示例代码不同的是,这里还按照官方说明添加了超时的时间设置,这里为10s,意思就是说十秒之内没有

任何通讯和消息传输就会关闭该连接。

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

完整nginx.conf配置文件

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

 map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }

    #gzip  on;

 upstream websocket {
  server 10.229.36.139:7777;
 }

    server {
        listen       88;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

  location /websocket/ {
            proxy_pass http://websocket;
            proxy_http_version 1.1;
   proxy_read_timeout 10s;
   proxy_send_timeout 10s;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

4、配置之后启动Nginx

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

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

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

异常断网的情况也是如此

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

Original: https://www.cnblogs.com/badaoliumangqizhi/p/16536639.html
Author: 霸道流氓
Title: Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/543603/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Spring Boot2 系列教程(三十二)Spring Boot 整合 Shiro

    在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro。 今天松哥就来和大家聊聊 Sp…

    Java 2023年5月30日
    087
  • [Docker] Dockerfile常用保留字

    FROM 基础镜像,当前新镜像是基于哪个镜像的,指定一个已经存在的镜像作为模板。第一条必须是from MAINTAINER 镜像维护者的姓名和邮箱地址 RUN 容器构建时需要运行的…

    Java 2023年6月5日
    087
  • java中变量的内存分配

    java中的变量大体分为:类(静态)变量、成员变量、局部变量,在class文件被jvm的类加载器加载后,随后这些变量被分配至内存中。但是,它们何时被分配至内存的何处呢? jvm把自…

    Java 2023年5月29日
    054
  • Mybatis的联合查询

    数据库表结构departmentemployee 要求一 现在的要求是输入 id 把 employee 表的对应员工数据查询出来,并且查询出该员工的所处部门信息 JavaBean …

    Java 2023年6月5日
    059
  • Spring(二)——IOC

    控制反转,把对象创建和对象之间的调用过程,交给 Spring 进行管理 目的:降低耦合度 xml 解析、工厂模式、反射 IOC接口 BeanFactory:IOC 容器基本实现,是…

    Java 2023年6月16日
    067
  • 关于计算两日期之间经过多少天的超巧妙算法

    首先声明:本文引自一博主原创博客 昨天呢,刚刚阅读了这个代码,大部分都还可以看懂,有一两个地方属实难懂,但细细思来,方知博主此代码超神奇。简直巧妙至极。 所以来细细解析一下此代码。…

    Java 2023年6月5日
    073
  • IDEA使用Gittee提交代码

    今天给大家分享一下如何从idea提交代码到gitee上面。1.先在gitee上创建仓库2.填写相应的信息3.下载git直接next一站式安装4.鼠标右键点击 Git Bash He…

    Java 2023年6月9日
    082
  • java mybatis 分页查询

    Page page = new Page(pageIndex + 1, pageSize); Page pagedData = signLogService.page(page,n…

    Java 2023年5月29日
    078
  • 关于 cannot create Parameters: [] 报错问题的解决方法

    其实在Sort类中添加无参构造就可以解决 我自己写的是Sort类,其它情况得视你们自己写的类决定 至于为什么也不是很清楚 Original: https://www.cnblogs…

    Java 2023年6月6日
    067
  • Java理解mian方法

    public static void mian (Sring[ ] args) public :提供给JVM调用的 static:jvm在调用这个方法是,不需要创建对象 void:…

    Java 2023年6月6日
    073
  • 记录获取图片的api接口

    二次元 https://api.ixiaowai.cn/api/api.php?return=jsonhttps: https://uploadbeta.com/api/pictu…

    Java 2023年6月5日
    069
  • IO多路复用

    先说明一个问题:在Java API中提供了两套NIO,一套是针对标准输入输出NIO,另一套就是网络编程NIO。网络编程其实就是多了一个连接的过程,常用在Netty一些框架。本文主要…

    Java 2023年6月7日
    098
  • JAVA日期格式YYYY-MM-DD与yyyy-MM-dd的区别

    有下面一段代码: csharp;gutter:true; public static void main(String[] args) { DateTime date = new …

    Java 2023年5月29日
    067
  • 下载excel文件,链接,通过按钮点击创建a标签实现

    html;gutter:true;let link = document.createElement(‘a’)link.style.display = ‘none’link.hre…

    Java 2023年5月29日
    050
  • mybatis-plus报错解决Invalid bound statement (not found)错误

    mybatis-plus报错解决Invalid bound statement (not found)错误 org.apache.ibatis.binding.BindingExc…

    Java 2023年5月30日
    090
  • 对象缓存服务的思考和实现

    写在前面 目前在很多业务中,存储都大量的依赖了云存储,比如阿里云的 oss、华为云的 obs 等。但是如果有大量的上传/下载任务,云存储上的网络 I/0 就变成了一个很大的瓶颈。 …

    Java 2023年6月7日
    070
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球