通信プロトコルの一種でPub/Sub型のデータ配信モデル。
軽量プロトコルのため、主にIoTの分野で使われていることが多いです。
Pub/Sub型に関わるのは次の3者。
履歴の残らないLINE、という感じでしょうか。
eclipse-mosquittoというMQTTサーバのdockerイメージが配布されています。
今回はホストの1883番ポートにmosquittoサーバを公開します。
さらにリバースプロキシの後ろに配置するため、nginxと同じnetwork(ここではdefault)に接続します。
docker-compose.yml(抜粋)
mosquitto:
image: eclipse-mosquitto
hostname: mosquitto
container_name: mosquitto
ports:
- "1883:1883"
volumes:
- ./mosquitto.conf:/mosquitto/config/mosquitto.conf
networks:
- default
moquitto.conf(一部)
# ========================================================
# Default listener
# ========================================================
# Port to use for the default listener.
port 1883
# Choose the protocol to use when listening.
protocol websockets
# listener port-number [ip address/host name]
listener 9001
nginx.conf(listen 443)
location /mqtt {
proxy_pass http://mosquitto:1883/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
import PahoMQTT from "paho-mqtt";
const uuidv4 = require('uuid/v4');
//wssを利用する
const client = new PahoMQTT.Client(
'******',443,uuidv4()
);
export const connect=()=>{
client.connect({
userName: "******",
password: "********",
useSSL: true,
onSuccess,
onFailure
});
client.onMessageArrived = onMessageArrived;
client.onConnectionLost = onConnectionLost;
}
const onSuccess=()=>{
client.subscribe(TOPIC);
}
const onFailure=()=>{
console.log('connect failed.')
}
export const onMessageArrived=(message)=>{
console.log(message.payloadString);
}
export const send=(message)=>{
client.send(TOPIC, message, 0, false);
}
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
connect();
}
}
2日目に登板予定です。
MQTTを基礎技術に使ったアプリを作る予定です。
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント