[TOC]
# 舉個栗子
底層庫是基于回調和事件驅動的操作。因此,您必須經常調用客戶端的`loop()`方法,以允許庫處理其隊列中的消息。你也可以使用`loopforever()`,這樣就不必頻繁調用方法。還有,您應該使用回調函數來確保您只在客戶端連接后再嘗試發布,等等。例如,以下是如何正確發布qos = 2消息的例子:
~~~
<?php
$c = new Mosquitto\Client;
$c->onConnect(function() use ($c) {
$c->publish('mgdm/test', 'Hello', 2);
$c->disconnect();
});
$c->connect('test.mosquitto.org');
// Loop around to permit the library to do its work
// This function will call the callback defined in `onConnect()`
// and disconnect cleanly when the message has been sent
$c->loopForever();
echo "Finished\n";
~~~
* * * * *