How does the connection message for mqtt via TCP look like?

828 views Asked by At

I'm currently working on a Website which should be a client that can connect to a MQTT broker. The broker I'm currently using is mosquitto. It's running on my local computer. The connection is also established, but to really work with the broker I'll need a connection message. But how does it look like?

That's the code I currently have, hope you guys can help me with it.

<?php
$address = '127.0.0.1';
$port = 1883;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() fehlgeschlagen: Grund: " . socket_strerror(socket_last_error()) . "\n";
}else {
    echo "OK.\n";
}

echo "Versuche, zu '$address' auf Port '$port' zu verbinden ...";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
    echo "socket_connect() fehlgeschlagen.\nGrund: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
}else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "clientId: clientid_12325334634\r\n";
$in .= "cleanSession: \r\n\r\n";

echo "HTTP HEAD request senden ...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

I'm working on a Windows computer and I'm using XAMPP.

1

There are 1 answers

2
hardillb On BEST ANSWER

MQTT is NOT HTTP, what you have written is not even close to being right, did you do any research on the protocol before starting?

If you really want to write a raw MQTT client then I suggest you read the spec -> http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html

Otherwise you should just use one of the existing PHP client libriaries -> https://github.com/mqtt/mqtt.github.io/wiki/libraries#php