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:

​
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;
 }

添加位置

这里的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;
        }

​

主要添加这两块

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

完整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秒没有消息就会关闭连接。

 异常断网的情况也是如此

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Nginx是一款高性能的Web服务器和反向代理服务器。它支持WebSocket协议,可以用于反向代理WebSocket连接。WebSocket是一种全双工通信协议,通过单个TCP连接,在客户端和服务器之间实现了实时数据的双向通信。 在使用Nginx作为WebSocket反向代理之前,我们需要确保Nginx编译安装时开启了WebSocket模块。接下来,我们可以通过在Nginx配置文件中进行一些配置来开启WebSocket反向代理。 首先,我们需要在http块中添加`map`指令,用于定义后端服务器的IP和端口。例如: ``` http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } ... } ``` 然后,在server块中添加一些配置项,用于处理WebSocket连接的请求。例如: ``` server { listen 80; server_name your_domain.com; location /websocket { proxy_pass http://backend_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } } ``` 这里,`/websocket`是用于处理WebSocket连接的路径,`http://backend_server`是后端服务器的地址。 当客户端发送WebSocket连接请求时,Nginx会将请求通过`proxy_pass`指令转发给后端服务器。同时,`proxy_http_version`和`proxy_set_header`指令用于设置请求的协议和头部信息。 最后,重启Nginx服务使配置生效。 通过上述配置Nginx就可以作为WebSocket的反向代理,将客户端的请求转发给后端服务器,并实现双向通信。这样就可以更灵活地部署WebSocket应用,提高系统的性能和负载均衡能力。 ### 回答2: nginx websocket反向代理是指使用nginx作为代理服务器,将外部的客户端请求转发给内部的websocket服务器。它常用于负载均衡、高可用性和安全性等方面。 首先,为了实现nginxwebsocket反向代理,需要安装支持websocketnginx模块。常用的模块有ngx_http_proxy_module和ngx_http_upstream_module。这些模块可以在编译nginx时加入,也可以通过第三方的包管理工具进行安装。 其次,配置nginx的反向代理需要修改nginx配置文件。可以通过编辑nginx.conf文件或单独的配置文件来完成。在配置中,需要指定代理服务器的监听端口、目标websocket服务器的地址和端口等信息。 配置完成后,当客户端发送websocket请求到nginx代理服务器时,nginx会根据配置将请求转发给目标websocket服务器。nginx会将客户端的请求头信息传递给websocket服务器,并在代理服务器和websocket服务器之间建立一个长连接来进行实时的双向通信。 此外,nginx还支持负载均衡和扩展性。可以配置多个目标websocket服务器,并使用nginx的负载均衡算法来分发请求,提高系统的吞吐量和可用性。同时,nginx还可以通过添加其他模块来扩展其功能,如安全性模块和缓存模块,以提供更全面的保护和优化。 总的来说,nginx websocket反向代理是一种常用的解决方案,可以提高系统的性能和安全性。通过合理的配置和使用,可以实现高可用性、负载均衡等功能,满足复杂的实时通信需求。 ### 回答3: Nginx是一款优秀的Web服务器软件,同时也是一款功能强大的反向代理服务器。为了支持WebSocket协议的反向代理Nginx需要进行一些额外的配置。 首先,需要在Nginx配置文件中开启WebSocket支持。可以通过在http或者server块内添加以下配置语句来实现: ``` location /websocket { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } ``` 其中,/websocket代理WebSocket地址,http://backend是实际提供WebSocket服务的后端服务器地址。 接着,需要在Nginx配置文件中配置反向代理的后端服务器地址,并加入upstream块中。例如: ``` upstream backend { server backend_server_ip:backend_server_port; } ``` 其中,backend_server_ip是实际提供WebSocket服务的后端服务器IP地址,backend_server_port是对应的端口号。 配置完成后,重启Nginx服务使配置生效。 通过上述配置Nginx会接收到客户端的WebSocket请求并将其转发给后端服务器,实现反向代理。同时,Nginx还通过设置Upgrade和Connection头部信息,确保WebSocket协议在代理上可以正常运行。 需要注意的是,Nginx的版本要求至少为1.3.13才能支持WebSocket的反向代理功能。 总结来说,通过在Nginx配置文件中开启WebSocket支持,并配置反向代理的后端服务器地址,就可以实现NginxWebSocket的反向代理。这样,Nginx可以在前端作为反向代理服务器,将客户端的WebSocket请求转发给后端提供WebSocket服务的服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霸道流氓气质

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值