Mosquitto-PHP Documentation
https://media.readthedocs.org/pdf/mosquitto-php/latest/mosquitto-php.pdf
由於網路上的資訊有點亂,所以整理一下自己有在用的並分享出來。
※發佈
$CLIENT_ID = "pubclient_" + getmypid(); //CLIENT_ID這個可以隨便取 try { $client = new Mosquitto\Client($CLIENT_ID); $client->setCredentials("帳號","密碼"); //有使用憑證的話,要給完整路徑及檔名 $client->setTlsCertificates('/etc/ssl/certs/DST_Root_CA_X3.pem'); $client->onConnect(function() use ($client) { // publish($topic, $payload, $qos, $retain) 當 retain為true 就是訊息會一直留在 broker 裡面 $client->publish("主題名稱", "訊息內容", 1, true); $client->disconnect(); }); $client->connect("主機IP", 1883); //connect($host, $port, $keepalive) $client->loopForever(); unset($client); } catch (Mosquitto\Exception $ex) { var_dump($ex); }
※訂閱
$CLIENT_ID = "pubclient_" + getmypid(); //CLIENT_ID這個可以隨便取 try { $client = new Mosquitto\Client($CLIENT_ID); $client->setCredentials("帳號","密碼"); //有使用憑證的話,要給完整路徑及檔名 $client->setTlsCertificates('/etc/ssl/certs/DST_Root_CA_X3.pem'); $client->connect("主機IP", 1883, 60); //connect($host, $port, $keepalive) $client->subscribe("主題名稱", 1); $client->onMessage(function($m) { echo $m->topic." ".$m->payload."\r\n"; //會取得訂閱資訊的topic及payload }); //10分鐘內沒收到訊息則切斷重連 while (true) { $client->loop(); //當發生下列狀態時就切斷連線,如果不需要做此判斷可以直接用下面的loopForever()讓它一直跑 if(date("Y-m-d H:i:s")>$this->limitTime) { $client->disconnect(); } } //$client->loopForever(); //如果設定loopforever的話就會一直處理 } catch (Mosquitto\Exception $ex) { var_dump($ex); }