0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.js の mqtt クライアント

Last updated at Posted at 2017-12-04

Node.js の mqtt クライアントの例です。
Arch Linux で動作の確認をしました。

確認したバージョン

$ node --version
v23.9.0

ライブラリーのインストール

sudo npm install -g mqtt

パブリッシュ

publish.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	publish.js
//
//					Dec/04/2017
//
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://localhost')
const topic = 'topic_1'

client.on('connect', function () {
	const today = new Date ()
	var ddx = (1900 + today.getYear ()) + "-" + (today.getMonth () +1)
	ddx += "-" + today.getDate () + " " + today.getHours()
	ddx += ":" + today.getMinutes () + ":" + today.getSeconds()
	client.publish(topic, ddx)
	console.log(ddx)
	client.publish(topic, 'Good Afternoon mqtt')
	client.publish(topic, 'こんにちは')
	client.end()
	console.error ("*** 終了 ***")
})

// ---------------------------------------------------------------

実行コマンド

export NODE_PATH=/usr/lib/node_modules
./publish.js

サブスクライブ

subscribe.js
#! /usr/bin/node
// ---------------------------------------------------------------
//	subscribe.js
//
//					Dec/04/2017
//
// ---------------------------------------------------------------
console.error ("*** 開始 ***")
var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://localhost')

client.on('connect', function () {
	client.subscribe('topic_1')
})

client.on('message', function (topic, message) {
  // message is Buffer
	console.log(message.toString())
})
// ---------------------------------------------------------------

実行コマンド

export NODE_PATH=/usr/lib/node_modules
./subscribe.js

localhost で mosquitto を動かす

$ sudo systemctl status mosquitto
● mosquitto.service - Mosquitto MQTT Broker daemon
     Loaded: loaded (/usr/lib/systemd/system/mosquitto.service; disabled; vendo>
     Active: active (running) since Tue 2021-01-12 15:54:42 JST; 35min ago
   Main PID: 10924 (mosquitto)
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?