官方介绍:
MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.
* Tested on local machine (Intel i7 8700K) with MQTTnet client and server running in the same process using the TCP channel. The app for verification is part of this repository and stored in /Tests/MQTTnet.TestApp.NetCore.
This library is available as a nuget package: https://www.nuget.org/packages/MQTTnet/
使用vs创建mqtt项目,选择winform项目,方便创建界面,查看相关数据信息。项目包括两个,server和client。
服务器端界面结构如下:
Server在程序中添加本机IP:
var ips = Dns.GetHostAddressesAsync(Dns.GetHostName());
foreach (var ip in ips.Result)
{
switch (ip.AddressFamily)
{
case AddressFamily.InterNetwork:
TxbServer.Text = ip.ToString();
break;
case AddressFamily.InterNetworkV6:
break;
}
}
添加一个Action ,用来想listbox中添加数据:
private Action _updateListBoxAction;
//在load方法中定义
//超过1000条数据时,自动删除第一个
//出现滚动条时,滚动条自动向下移动
_updateListBoxAction = new Action((s) =>
{
listBox1.Items.Add(s);
if (listBox1.Items.Count > 1000)
{
listBox1.Items.RemoveAt(0);
}
var visibleItems = listBox1.ClientRectangle.Height/listBox1.ItemHeight;
listBox1.TopIndex = listBox1.Items.Count - visibleItems + 1;
});
//添加按键事件,按c时清空listbox
listBox1.KeyPress += (o, args) =>
{
if (args.KeyChar == 'c' || args.KeyChar=='C')
{
listBox1.Items.Clear();
}
};
mqttserver
private async void MqttServer()
{
if (null != _mqttServer)
{
return;
}
var optionBuilder =
new MqttServerOptionsBuilder().WithConnectionBacklog(1000).WithDefaultEndpointPort(Convert.ToInt32(TxbPort.Text));
if (!TxbServer.Text.IsNullOrEmpty())
{
optionBuilder.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(TxbServer.Text));
}
var options = optionBuilder.Build();
(options as MqttServerOptions).ConnectionValidator += context =>
{
if (context.ClientId.Length < 10)
{
context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
return;
}
if (!context.Username.Equals("admin"))
{
context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
return;
}
if (!context.Password.Equals("public"))
{
context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
return;
}
context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
};
_mqttServer = new MqttFactory().CreateMqttServer();
_mqttServer.ClientConnected += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction, $">Client Connected:ClientId:{args.ClientId},ProtocalVersion:");
var s = _mqttServer.GetClientSessionsStatusAsync();
label3.BeginInvoke(new Action(() => { label3.Text = $"连接总数:{s.Result.Count}"; }));
};
_mqttServer.ClientDisconnected += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction, $" { label3.Text = $"连接总数:{s.Result.Count}"; }));
};
_mqttServer.ApplicationMessageReceived += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction,
$"ClientId:{args.ClientId} Topic:{args.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)} QualityOfServiceLevel:{args.ApplicationMessage.QualityOfServiceLevel}");
};
_mqttServer.ClientSubscribedTopic += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction, $"@ClientSubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Topic} QualityOfServiceLevel:{args.TopicFilter.QualityOfServiceLevel}");
};
_mqttServer.ClientUnsubscribedTopic += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction, $"%ClientUnsubscribedTopic ClientId:{args.ClientId} Topic:{args.TopicFilter.Length}");
};
_mqttServer.Started += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Start...");
};
_mqttServer.Stopped += (sender, args) =>
{
listBox1.BeginInvoke(_updateListBoxAction, "Mqtt Server Stop...");
};
await _mqttServer.StartAsync(options);
}
把mqttserver中定义的事件都进行了绑定
(options as MqttServerOptions).ConnectionValidator 为进行mqttclient连接时进行的验证工作
想要查看完整代码,请移步到gitee
https://gitee.com/sesametech-group/MqttNetSln
你感觉文章还可以,移步到gitee上给个star