PHP is a widely used open source multi-purpose scripting language, which can be embedded in HTML, especially suitable for Web development.
This article mainly introduces how to use php-mqtt/client
client library of connection, subscription, unsubscription, sending and receiving messages MQTT client and MQTT server 1610913aeab576.
MQTT client library selection
php-mqtt/client
which has the highest download on composer. More PHP-MQTT client libraries can be viewed in Packagist-Search MQTT .
For more documentation about php-mqtt/client, please refer to Packagist php-mqtt/client .
MQTT communication belongs to the network communication scenario outside the HTTP system. Due to the limitation of PHP characteristics, the use of Swoole/Workerman in the PHP system and other extensions designed for network communication can bring a better experience. Its use will not be repeated in this article. The MQTT client library is as follows:
- workerman/mqtt:Asynchronous MQTT client for PHP based on workerman.
- simps/mqtt:MQTT Protocol Analysis and Coroutine Client for PHP.
Project initialization
Confirm PHP version
This project uses 7.4.21 for development and testing. Readers can confirm the PHP version with the following command.
php --version
PHP 7.4.21 (cli) (built: Jul 12 2021 11:52:30) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
with Zend OPcache v7.4.21, Copyright (c), by Zend Technologies
Use Composer to install the php-mqtt/client client
Composer is a dependency management tool for PHP, which can manage all the dependencies required by your PHP project.
composer require php-mqtt/client
PHP MQTT use
Connect to MQTT server
This article will use the free public MQTT server provided by EMQ X, which is based on the 1610913aeab71e MQTT IoT cloud platform Server access information is as follows:
- Broker: broker-cn.emqx.io
- TCP Port: 1883
- SSL/TLS Port: 8883
Import composer autoload file and php-mqtt/client
require('vendor/autoload.php');
use \PhpMqtt\Client\MqttClient;
Set MQTT Broker connection parameters
Set the MQTT Broker connection address, port and topic, and at the same time we call the PHP rand
function to randomly generate the MQTT client id.
$server = 'broker-cn.emqx.io';
$port = 1883;
$clientId = rand(5, 15);
$username = 'emqx_user';
$password = null;
$clean_session = false;
Write MQTT connection function
Use the above parameters to connect, set the connection parameters ConnectionSettings
$connectionSettings = new ConnectionSettings();
$connectionSettings
->setUsername($username)
->setPassword(null)
->setKeepAliveInterval(60)
// Last Will 设置
->setLastWillTopic('emqx/test/last-will')
->setLastWillMessage('client disconnect')
->setLastWillQualityOfService(1);
Subscribe to news
Write code to subscribe to the emqx/test
, and configure a callback function for the subscription to process the received message, here we will print out the topic and message obtained by the subscription:
// 订阅
$mqtt->subscribe('emqx/test', function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
release the news
Construct a payload, call publish
function to emqx/test
announced theme, released after the completion of the client needs to enter the polling state, processing incoming messages and resend queue:
for ($i = 0; $i< 10; $i++) {
$payload = array(
'protocol' => 'tcp',
'date' => date('Y-m-d H:i:s'),
'url' => 'https://github.com/emqx/MQTT-Client-Examples'
);
$mqtt->publish(
// topic
'emqx/test',
// payload
json_encode($payload),
// qos
0,
// retain
true
);
printf("msg $i send\n");
sleep(1);
}
// 客户端轮询以处理传入消息和重发队列
$mqtt->loop(true);
Complete code
Server connection, message publishing and receiving code.
<?php
require('vendor/autoload.php');
use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
$server = 'broker.emqx.io';
$port = 1883;
$clientId = rand(5, 15);
$username = 'emqx_user';
$password = null;
$clean_session = false;
$connectionSettings = new ConnectionSettings();
$connectionSettings
->setUsername($username)
->setPassword(null)
->setKeepAliveInterval(60)
// Last Will 设置
->setLastWillTopic('emqx/test/last-will')
->setLastWillMessage('client disconnect')
->setLastWillQualityOfService(1);
$mqtt = new MqttClient($server, $port, $clientId);
$mqtt->connect($connectionSettings, $clean_session);
printf("client connected\n");
$mqtt->subscribe('emqx/test', function ($topic, $message) {
printf("Received message on topic [%s]: %s\n", $topic, $message);
}, 0);
for ($i = 0; $i< 10; $i++) {
$payload = array(
'protocol' => 'tcp',
'date' => date('Y-m-d H:i:s'),
'url' => 'https://github.com/emqx/MQTT-Client-Examples'
);
$mqtt->publish(
// topic
'emqx/test',
// payload
json_encode($payload),
// qos
0,
// retain
true
);
printf("msg $i send\n");
sleep(1);
}
$mqtt->loop(true);
test
Run the MQTT message publishing code, we will see that the client has successfully connected, and the messages have been published one by one and received successfully:
php pubsub_tcp.php
Summarize
So far, we have completed using the php-mqtt/client client to connect to the public MQTT server , and realized the connection between the test client and the MQTT server, message publishing and subscription.
Copyright notice: This article is the EMQ , please indicate the source for reprinting.
Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-php
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。