mqtt php物联网,用 PHP 通过 MQTT 物联网协议实现消息传送

MQTT 是物联网的消息传送协议标准。

在 CentOS 7上常用的开源 MQTT 消息服务器就是 Mosquitto。

我们用 PECL 来安装 Mosquitto 的 PHP 实现。

首先要确保 php-devel 已经安装:

# yum install -y php-devel

然后确保 mosquitto-devel 也已经安装:

#yum install -y mosquitto-devel

# pecl install Mosquitto-alpha

然后去  /etc/php.ini 添加一行:

extension=mosquitto.so

重启 Apache后,运行 php -i|grep mosquitto 可以看到

mosquitto

libmosquitto version => 1.4.13

表明 PHP 可以使用 mosquitto 的 MQTT 库了。

下面是用 PHP 来发送消息的示例代码 mosquitto-test.php:

2

3

4 $c = new Mosquitto\Client;

5

6 $topic = ‘test’;

7 $msg = ‘hello你好’;

8 $qos = 2;

9

10 $username = ‘username’;

11 $password = ‘Passw0rd’;

12

13 $c->setCredentials($username, $password);

14 $c->onConnect(function() use ($c) {

15 global $topic,$msg,$qos;

16 $c->publish($topic, $msg, $qos);

17 });

18

19 $host = ‘192.168.7.201’;

20

21 $c->connect($host);

22 for ($i = 0; $i < 100; $i++) {

23 // Loop around to permit the library to do its work

24 $c->loop(1);

25 }

26

27 echo “结束\n”;

然后运行 php mosqitto-test.php

另外开启一个终端,用

# mosquitto_sub -h 192.168.7.201 -u username -P Passw0rd -t test

可以看到 PHP 程序发送的消息: “hello你好”.

作者: 甬洁网络

--移动互联网&物联网技术提供商 查看甬洁网络的所有文章

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值