如何使用 python 在 paho 中增加每秒的消息数

How to increase messages per second in paho using python

我正在使用 Eclipse 的 paho-mqtt。 我在 Raspberry Pi 3 B+ 和笔记本电脑 运行 Ubuntu 16.04 上安装了 Paho。我使用 LAN 电缆将 Raspberry Pi 连接到笔记本电脑。我正在使用我的笔记本电脑作为服务器,即我正在使用本地主机作为服务器。

我从 Raspberry Pi 发布消息,每秒只能发布大约 200 条消息。另一方面,我的笔记本电脑是订阅者,我每秒只能收到大约 20-25 条消息。 我附上了发布者和订阅者的代码。如何发送更多消息?

发布商代码:

import paho.mqtt.publish as mqtt
import time
import serial

ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
time.sleep(2)

a = time.time()
num = 0

while (time.time() - a) < 1.0:
    try:
        data = int(ser.readline())
        mqtt.single("test", data, hostname="10.42.0.1")
        num = num + 1
    except ValueError:
        None

print(num)
ser.close()

订阅者代码:

import paho.mqtt.subscribe as mqtt
import time

b=0
a = time.time()

while True:
    msg = mqtt.simple("0", hostname="10.42.0.1")
    b=b+1
    print(msg.payload, b)

首先,串口IO速度慢;

其次,如果你阅读 paho-mqtt 的文档或源代码,你会发现 mqtt.single() 为每个函数调用创建一个新的 TCP 连接,它会影响性能,我建议你使用mqtt.Client class 完成任务;

最后,如果 Pub 的速率真的很重要,那么存在一个 C 实现 MQTT client