如何在node.js和python之间保持连接状态?

3

我有一个基于Node.js和Python硬件的Web应用程序。 我想保持Web服务器和硬件之间的连接状态。 如果硬件从Web应用程序断开连接,则Web应用程序应该获得事件或通知,以便我可以向用户发送通知。 我使用了MQTT进行数据通信,但为了保持连接状态,我不能使用MQTT,因为它与代理连接。 我不想在服务器上增加更多负载。

哪些工具/技术/协议/方法应该使用来保持设备的离线或在线状态? 当用户尝试使用Web应用程序向硬件发送数据时,如果设备未连接到服务器,则用户应该根据连接状态收到设备离线的通知。


去了解一下MQTT的“遗嘱”功能和保留消息。 - hardillb
@hardillb 感谢您的建议,这将部分解决我的问题。当设备断开连接时,我会收到消息,那么有没有办法检测设备何时重新联机? - Krunal Sonparate
1
更加深入地思考它,你只需要一个自动的方法来处理设备离线的情况,当事物重新上线时,它们将完全受到你的控制。 - hardillb
1个回答

2
以下代码演示了我在评论中提到的过程。
LWT功能告诉代理在1.5倍的保持连接期间内无法响应时发布一条消息,将客户端标记为离线。如果客户端正常断开连接,则需要将其标记为离线。当客户端连接到代理时,它会将自己标记为在线状态。
所有状态消息都设置了保留位,因此当客户端订阅状态主题时,它们将始终被传递。
import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("some/application/topic")
    # set status message to online
    client.publish("status/client1", payload="online", retain=True)

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

    if str(msg.payload) == "shutdown":
        # update status to offline as this will be a clean dissconect
        client.publish("status/client1", payload="offline", retain=True)
        client.disconnect()

client = mqtt.Client(client_id="client1")
client.on_connect = on_connect
client.on_message = on_message
client.will_set("status/client1", payload="offline", retain=True)

client.connect("mqtt.eclipse.org", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

在问题结束时,向离线客户端发送消息的通知实现将由OP负责。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接