Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Mosquittoをwebsocket対応にさせる その2:mqttws31を動かす

shuzo-kino.hateblo.jp
の続きです。
まずはbottle抜きで有名所のJS製MQTTクライアントmqttws31を動かしてみます

実際のところ

まずはindex.html。
mqttws31はCDN版を借りてきます。
そっけないので、本文に"sample"とか書いてますが、ここはお好みで。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TEST</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="client.js"></script>
</head>
<body>
<p>sample</p>
</body>
</html>

"client.js"はこんな塩梅。
元ネタはconsole.logなんてハイカラなものを使ってますが
縄文人の私はalertで楽をします

// Create a client instance
var client = new Paho.MQTT.Client("localhost", 9090 , "clientId" + new Date().getTime());

// set callback handlers
client.onMessageArrived = onMessageArrived;

// connect the client
client.connect({onSuccess:onConnect});

// called when the client connects
function onConnect() {
    // Once a connection has been made, make a subscription and send a message.
    alert("onConnect");
    client.subscribe("PUBLIC/log/#");
}

// called when a message arrives
function onMessageArrived(message) {
    alert('payload: ' + message.payloadString);
}

動かす

前の記事で設定したwebsockets対応鯖を立ち上げ、
publisherで投稿してみます。

$ mosquitto_pub -h localhost -t PUBLIC/log/a -m 64 -q 1

なにかミスってなければ、"payload: 64"と期待した通りにでます。
f:id:shuzo_kino:20171018233012p:plain