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);