当前位置: 代码迷 >> 综合 >> [Mosquitto]奇怪!每隔120s就重连一次!Socket error on...错误
  详细解决方案

[Mosquitto]奇怪!每隔120s就重连一次!Socket error on...错误

热度:100   发布时间:2023-11-11 03:16:58.0

Nginx代理webSocket经常中断的解决方法(也就是如何保持长连接)

初次使用IP连接时,并没有出现这种情况。之后对mosquitto服务配置了域名后,客户端client才出现了频繁重连的情况,那么基本可以确定是网络相关的配置出现问题。

  • 首先需要nginx来帮助frp作更细致的反向代理配置,这里主要是增加了ws的支持和增加了超时时间:

    #PROXY-START/
    location  ~* \.(php|jsp|cgi|asp|aspx)$
    {proxy_pass http://127.0.0.1:23456;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header REMOTE-HOST $remote_addr;proxy_connect_timeout 4s;                #配置点1proxy_read_timeout 120s;          #配置点2,如果没效,可以考虑这个时间配置长一点proxy_send_timeout 12s;                  #配置点3proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade";
    }
    location /
    {proxy_pass http://127.0.0.1:23456;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header REMOTE-HOST $remote_addr;add_header X-Cache $upstream_cache_status;proxy_connect_timeout 4s;                #配置点1proxy_read_timeout 120s;          #配置点2,如果没效,可以考虑这个时间配置长一点proxy_send_timeout 12s;                  #配置点3proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade";#Set Nginx Cacheadd_header Cache-Control no-cache;expires 12h;
    }#PROXY-END/
    
  • 然后就是mosquitto的使用过程中增加心跳包发送,规定每隔30s就发送一次心跳包

    • js:

      const options = {
              keepalive:30
      };
      const client = mqtt.connect(host, options);
      
    • python:

      client.connect(host=HOST,port=PORT,keepalive=30)
      

MINE MIND系列将在我的GitHub上实时更新,同时精选部分汇总于CSDN专栏
GitHub仓库:https://github.com/IcyLeaves/MINE-MIND
CSDN专栏:https://blog.csdn.net/qq_37398834/category_10975647.html

  相关解决方案