「マイクロソフト系技術情報 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。
MQTTブローカーのOSS
送信する人
受信する人
送受信対象のメッセージ
キュー
http://mosquitto.org/download/
>cd C:\Program Files\Mosquitto >mosquitto -v
>cd C:\Program Files\Mosquitto >mosquitto_sub -h 127.0.0.1 -t "#" -v
>cd C:\Program Files\Mosquitto >mosquitto_pub -h 127.0.0.1 -t test -m "hoge"
$ sudo add-apt-repository ppa:mosquitto-dev/mosquitto-ppa
$ sudo apt-get install mosquitto mosquitto-clients
$ sudo apt-get install mosquitto
$ sudo apt-get install mosquitto-clients
ミドルウェアなので、コチラの作法で動かせるっぽい。
(ただし、コンフィグ・ファイルの準備は必要)
https://github.com/OpenTouryoProject/DxCommon/tree/develop/Edge/Mosquitto/IaC
...
最近、更新頻度が落ちてきている。
using System;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace M2MqttSub
{
class Program
{
static void Main(string[] args)
{
var client = new MqttClient("127.0.0.1");
client.MqttMsgPublishReceived += (sender, eventArgs) =>
{
var msg = Encoding.UTF8.GetString(eventArgs.Message);
var topic = eventArgs.Topic;
Console.WriteLine(topic + ", " + msg);
};
var ret = client.Connect(Guid.NewGuid().ToString());
Console.WriteLine("Connected with result code {0}", ret);
client.Subscribe(new[] { "test" }, new[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
while (client.IsConnected)
{
}
}
}
}using System;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
namespace M2MqttPub
{
class Program
{
static void Main(string[] args)
{
var client = new MqttClient("127.0.0.1");
var ret = client.Connect(Guid.NewGuid().ToString());
Console.WriteLine("Connected with result code {0}", ret);
while (client.IsConnected)
{
var msg = "Test message from Publisher " + DateTime.Now;
client.Publish("test", Encoding.UTF8.GetBytes(msg), 0, true);
Console.WriteLine("Message published.");
System.Threading.Thread.Sleep(1500);
}
}
}
}更新が頻繁で、トータル・ダウンロードがPaho M2Mqttの4倍以上
using System;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Receiving;
using System.Security.Cryptography.X509Certificates;
namespace msqt_sub
{
class Program
{
private static IMqttClient mqttClient = null;
static async Task Main(string[] args)
{
X509Certificate2 ca = new X509Certificate2("ca.crt");
X509Certificate2 cli = new X509Certificate2("client.pfx", "xxxxx");
var factory = new MqttFactory();
Program.mqttClient = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithClientId("ef3614fca42b32d3")
.WithTcpServer("localhost", 8883)
.WithCredentials("guest", "guest")
.WithTls(new MqttClientOptionsBuilderTlsParameters(){
UseTls = true,
SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
AllowUntrustedCertificates = true,
//CertificateValidationCallback = (a, b, c, d) => true,
CertificateValidationHandler = (o) =>
{
Console.WriteLine(o.ToString());
return true;
},
Certificates = new List<X509Certificate>()
{
ca, cli
}
})
.Build();
// 接続後のイベントハンドラの設定
Program.mqttClient.ApplicationMessageReceivedHandler
= new MqttApplicationMessageReceivedHandlerDelegate(OnAppMessage);
Program.mqttClient.ConnectedHandler
= new MqttClientConnectedHandlerDelegate(OnConnected);
// 接続
await Program.mqttClient.ConnectAsync(options);
// 待機
Console.ReadLine();
}
static private async void OnConnected(MqttClientConnectedEventArgs e) {
await Program.mqttClient.SubscribeAsync(
new TopicFilterBuilder()
.WithTopic("test").Build());
}
static private void OnAppMessage(MqttApplicationMessageReceivedEventArgs e)
{
string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
Console.WriteLine(payload);
}
}
}using System;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System.Security.Cryptography.X509Certificates;
namespace msqt_pub
{
class Program
{
private static IMqttClient mqttClient = null;
static async Task Main(string[] args)
{
X509Certificate2 ca = new X509Certificate2("ca.crt");
X509Certificate2 cli = new X509Certificate2("client.pfx", "xxxxx");
var factory = new MqttFactory();
Program.mqttClient = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithClientId("ef3614fca42b32d3")
.WithTcpServer("localhost", 8883)
.WithCredentials("guest", "guest")
.WithTls(new MqttClientOptionsBuilderTlsParameters(){
UseTls = true,
SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
AllowUntrustedCertificates = true,
//CertificateValidationCallback = (a, b, c, d) => true,
CertificateValidationHandler = (o) =>
{
Console.WriteLine(o.ToString());
return true;
},
Certificates = new List<X509Certificate>()
{
ca, cli
}
})
.Build();
// 接続
await Program.mqttClient.ConnectAsync(options);
// メッセージの送信するための設定
var message = new MqttApplicationMessageBuilder()
.WithTopic("test")
.WithPayload("hoge")
.WithExactlyOnceQoS()
.Build();
// メッセージの送信 publish
await Program.mqttClient.PublishAsync(message);
}
}
}証明書認証(サーバー認証とクライアント認証)+パスワード認証を構成し、Paho M2Mqtt、MQTTnetからアクセスする。
>openssl req -new -x509 -days 365 -extensions v3_ca -keyout ca.key -out ca.crt Generating a RSA private key ................................................+++++ ............+++++ writing new private key to 'ca.key' Enter PEM pass phrase: Verifying - Enter PEM pass phrase: ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:JP State or Province Name (full name) [Some-State]: Locality Name (eg, city) []: Organization Name (eg, company) [Internet Widgits Pty Ltd]: Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:hogeca Email Address []:
>openssl genrsa -out server.key 2048 Generating RSA private key, 2048 bit long modulus (2 primes) ..............+++++ e is 65537 (0x010001)
>openssl req -out server.csr -key server.key -new You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:JP State or Province Name (full name) [Some-State]: Locality Name (eg, city) []: Organization Name (eg, company) [Internet Widgits Pty Ltd]: Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:localhost Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:
>openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365 Signature ok subject=C = JP, ST = Some-State, O = Internet Widgits Pty Ltd, CN = localhost Getting CA Private Key Enter pass phrase for ca.key:
listener 8883 cafile ./certs/ca.crt certfile ./certs/server.crt keyfile ./certs/server.key allow_anonymous true
>cd C:\Program Files\Mosquitto >mosquitto -v -c mosquitto.conf
>cd C:\Program Files\Mosquitto >mosquitto_sub -h localhost -t "#" -v -d -p 8883 --cafile <ca.crtのパス>
>cd C:\Program Files\Mosquitto >mosquitto_pub -h localhost -t test -m "hoge" -d -p 8883 --cafile <ca.crtのパス>
>openssl genrsa -out client.key 2048 Generating RSA private key, 2048 bit long modulus (2 primes) ......+++++ e is 65537 (0x010001)
>openssl req -out client.csr -key client.key -new You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]: State or Province Name (full name) [Some-State]: Locality Name (eg, city) []: Organization Name (eg, company) [Internet Widgits Pty Ltd]: Organizational Unit Name (eg, section) []: Common Name (e.g. server FQDN or YOUR name) []:hogecli Email Address []: Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []:
>openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365 Signature ok subject=C = AU, ST = Some-State, O = Internet Widgits Pty Ltd, CN = hogecli Getting CA Private Key Enter pass phrase for ca.key:
require_certificate true
>cd C:\Program Files\Mosquitto >mosquitto -v -c mosquitto.conf
--cert <client.crtのパス> --key <client.keyのパス>
>cd C:\Program Files\Mosquitto >mosquitto_passwd -c pwfile guest Password: Reenter password:
allow_anonymous false password_file /etc/mosquitto/pwfile
>cd C:\Program Files\Mosquitto >mosquitto -v -c mosquitto.conf
-u guest -P guest
>openssl pkcs12 -export -out client.pfx -inkey client.key -in client.crt Enter Export Password: Verifying - Enter Export Password:
X509Certificate2 ca = new X509Certificate2("ca.crt");
X509Certificate2 cli = new X509Certificate2("client.pfx", "xxxxx");
var client = new MqttClient("localhost", 8883, true, ca, cli, MqttSslProtocols.TLSv1_2);
client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
var ret = client.Connect(Guid.NewGuid().ToString(), "guest", "guest");コチラの実装で動作すると思う。
req: Can't open "ファイル名" for writing, Permission denied
sudo chmod 644 server.key
listener 8883 cafile /etc/mosquitto/certs/ca.crt certfile /etc/mosquitto/certs/server.crt keyfile /etc/mosquitto/certs/server.key allow_anonymous true
$ sudo systemctl restart mosquitto
※ ca_certificatesフォルダがあったので、
CAのファイルはそちらに配置した方が良いカモ。
req: Can't open "ファイル名" for writing, Permission denied
sudo chmod 644 client.key
require_certificate true
$ sudo systemctl restart mosquitto
Error: Unable to open file pwfile for writing. Permission denied.
allow_anonymous false password_file ./pwfile
$ sudo systemctl restart mosquitto
Error: Unable to open file pwfile for writing. Permission denied.
$ dotnet new console
コチラの実装で動作した。
正規のCN、場合によっては、
証明書ストアへの登録が必要なのかもしれない。