MQTT 消息在 React 中的 Websockets 上打开太多 TCP 连接

MQTT messages opening too many TCP connections on Websockets in React

我有一个 ESP32 设备使用 umqtt 模块以非常快的速度发送数据。此外,Mosquitto 代理在端口 1883 上侦听 mqtt,在端口 9001 上侦听 websockets。最后,一个实时显示消息的 React App。

问题是每次React App收到来自ESP设备的消息时,都会建立一个新的TCP连接,导致打开了很多连接,如下所示:

pi@rthree:/etc/mosquitto $ ss -s
Total: 449
TCP:   334 (estab 257, closed 70, orphaned 0, timewait 68)

Transport Total     IP        IPv6
RAW   1         0         1        
UDP   6         3         3        
TCP   264       261       3        
INET      271       264       7        
FRAG      0         0         0   

如何解决连接过载问题?

有什么建议吗?

在前端,这是React App:

import {useEffect,useState} from 'react'
import './App.css';
import mqtt from "mqtt";

function App() {
const [mess, setMess] = useState("0")

const options = {"username":"user","password":"password"}
const client = mqtt.connect("ws://192.168.1.166:9001",options);
client.subscribe("temp_orientation");

const update_mqtt = () =>{
    client.on("message", function (topic, message) {
      const mssg = message.toString();
      setMess(mssg);
         
    } )
}
useEffect(()=>{
    update_mqtt();
},[])

  return (
    <div className="App">
      <header className="App-header">

      <h1>Data: {mess}</h1>
      </header>
    </div>
  );
}

export default App;

这是后端:

import mpu6050
from machine import SoftI2C, Pin, PWM, ADC, reset
from time import sleep
import network
import wifi
import math

from umqtt import robust as mqtt

try:
    wifi.wifi_connect()
except:
    wifi.hotspot_connect()

mqtt_server = "192.168.1.166"
client_id = "usero"
topic_sub = 'temp_orientation'

def sub_cb(topic, msg):
  print(topic, msg)


def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = mqtt.MQTTClient(client_id, mqtt_server,user='user00001', password='password')
  client.set_callback(sub_cb)
  client.connect()
  client.subscribe(topic_sub)
  return client

def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  sleep(1)
  reset()

try:
  client = connect_and_subscribe()
except OSError as e:
  restart_and_reconnect()

# mpu sensor

i2c = SoftI2C(scl=Pin(22),sda=Pin(21))
a = mpu6050.accel(i2c)

tprev = 0
mprev = False
m = 0

while True:
    
    values = a.get_values()
    z = values["AcZ"]
    t = math.floor(int(values["Tmp"]) * 10) / 10
    
    if int(z) < 0:
        m = "DOWN"
        
    if int(z) > 0:
        m = "UP"
     
    if t != tprev or m != mprev:
        mprev = m
        tprev = t
        try:
            client.check_msg()
            client.publish("temp_orientation", "{} {}".format(str(t),m))
        
        except OSError as e:
            restart_and_reconnect()
                      
    sleep(0.2)

谢谢。

将所有mqtt逻辑常量移入useEffect后解决。现在它会在收到每条消息后更新状态,并且不会保持连接打开。

import {useEffect,useState} from 'react'
import './App.css';
import mqtt from "mqtt";

function App() {
const [mess, setMess] = useState("0")

useEffect(()=>{
    const options = {"username":"user","password":"password"}
    const client = mqtt.connect("ws://192.168.1.166:9001",options);
    client.subscribe("temp_orientation");
    const update_mqtt = () =>{
        client.on("message", function (topic, message) {
            const mssg = message.toString();
            setMess(mssg);
         } )
}
    update_mqtt();
},[])

  return (
    <div className="App">
      <header className="App-header">

      <h1>Data: {mess}</h1>
      </header>
    </div>
  );
}

export default App;