我正在使用 Mosquitto/Client php 库。我已经在经纪人和客户之间建立了正确的连接。当我执行发布者和订阅者时,订阅者会显示许多消息,但我想在发布者发布消息时获得一条已发布的消息。我将如何通过订阅已发布的消息获得单条消息?
订阅者.php
define('BROKER', '192.168.0.13');
define('PORT', 1883);
define('CLIENT_ID', "pubclient_" + getmypid());
$client = new Mosquitto\Client(CLIENT_ID);
$client->onConnect('connect');
$client->onDisconnect('disconnect');
$client->onSubscribe('subscribe');
$client->onMessage('message');
$client->connect(BROKER, PORT, 60);
$client->subscribe('test/foo/bar', 1);
$client->loopForever();
function connect($r) {
echo "Received response code {$r}\n";
}
function subscribe() {
echo "Subscribed to a topic\n";
}
function message($message) {
printf("Got a message on topic %s with payload:\n%s\n", $message->topic, $message->payload);
}
function disconnect() {
echo "Disconnected cleanly\n";
}
发布者.php
define('BROKER', '192.168.0.13');
define('PORT', 1883);
define('CLIENT_ID', "pubclient_" + getmypid());
$client = new Mosquitto\Client(CLIENT_ID);
$client->connect(BROKER, PORT, 5);
while ($client->loop() == 0) {
$message = "Test message at " . date("Y-m-d H:i:s");
$client->publish('test/foo/bar', $message, 1, false);
$client->loop();
sleep(1);
}
我想在特定的时间间隔内发布/订阅。Publisher.php 在间隔时间段内发布带有消息的主题,subscriber.php 在间隔时间段内获取带有该消息的主题。