mqtt实例 php_php实现mqtt发布/发送 消息到主题

这篇博客介绍了如何使用PHP实现MQTT协议,通过创建socket连接到MQTT服务器进行消息的发布和订阅。示例代码展示了一个Mqtt类的实现,包括连接、发布消息、订阅主题和处理收到的消息。此外,还提到了使用JavaScript进行类似功能开发的简易性。
摘要由CSDN通过智能技术生成

php实现mqtt发布/发送 消息到主题mqtt是啥?我的博客有写这个东西:传送门

php想要实现mqtt需要使用到php中的socket函数;

此次使用的是网上开源mqtt案例:其中使用的是 stream_socket_xxxx 系列函数

大概意思是:正如你所指出的,'stream'是PHP核心(内置的,始终可用),而'套接字'是很少包含的扩展的一部分。除此之外,它们几乎完全相同。您可以同时使用TCP和UDP两种流,也可以使用阻塞和非阻塞模式,这些模式涵盖了所有用例的99%。

我能想到的唯一常见的例外是ICMP。例如,'ping'。但是,看起来目前还没有一种安全的方式来从PHP执行ICMP。这种调用需要通过套接字扩展来实现SOCK_RAW,这需要执行“root”权限。此外,并非所有路由器都会在TCP,UDP和ICMP之外路由其他数据包类型。这限制了套接字扩展的实用性。

MQTT类代码:/* phpMQTT */

class Mqtt {

private $socket; /* holds the socket */

private $msgid = 1; /* counter for message id */

public $keepalive = 10; /* default keepalive timmer */

public $timesinceping; /* host unix time, used to detect disconects */

public $topics = array(); /* used to store currently subscribed topics */

public $debug = false; /* should output debug messages */

public $address; /* broker address */

public $port; /* broker port */

public $clientid; /* client id sent to brocker */

public $will; /* stores the will of the client */

private $username; /* stores username */

private $password; /* stores password */

public $cafile;

function __construct($address, $port, $clientid, $cafile = NULL){

$this->broker($address, $port, $clientid, $cafile);

}

/* sets the broker details */

function broker($address, $port, $clientid, $cafile = NULL){

$this->address = $address;

$this->port = $port;

$this->clientid = $clientid;

$this->cafile = $cafile;

}

function connect_auto($clean = true, $will = NULL, $username = NULL, $password = NULL){

while($this->connect($clean, $will, $username, $password)==false){

sleep(10);

}

return true;

}

/* connects to the broker

inputs: $clean: should the client send a clean session flag */

function connect($clean = true, $will = NULL, $username = NULL, $password = NULL){

if($will) $this->will = $will;

if($username) $this->username = $username;

if($password) $this->password = $password;

if ($this->cafile) {

$socketContext = stream_context_create(["ssl" => [

"verify_peer_name" => true,

"cafile" => $this->cafile

]]);

$this->socket = stream_socket_client("tls://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT, $socketContext);

} else {

$this->socket = stream_socket_client("tcp://" . $this->address . ":" . $this->port, $errno, $errstr, 60, STREAM_CLIENT_CONNECT);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值