C#建立MQTT服务器(基于MQTTnet,局域网)
最近在做一套测量系统,部分用到ESP8266测量上传数据,所以在局域网内首选了MQTT协议来做,主要是方便以后可能会需要拓展到公网服务器做准备。
先来看一下窗体
看一下需要用到的库
应该不用我教大家怎么调入MQTTnet包吧(NuGet包)
下面是具体的内容:
namespace MQTT_STA
{
public partial class Form1 : Form
{
int lianjie = 0;
public delegate void MyInvoke(string str1, string str2, string str3, string str4);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
StartMqttServer();
}
public MqttServer mqttServer = null;
public async void StartMqttServer()
{
try
{
if (mqttServer == null)
{
var optionsBuilder = new MqttServerOptionsBuilder()
.WithDefaultEndpoint().WithDefaultEndpointPort(Convert.ToInt32(textBox1.Text)).WithConnectionValidator(
c =>
{
if (!c.Username.Equals(textBox3.Text.ToString()))
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
if (!c.Password.Equals(textBox2.Text.ToString()))
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
c.ReasonCode = MqttConnectReasonCode.Success;
}).WithSubscriptionInterceptor(
c =>
{
c.AcceptSubscription = true;
}).WithApplicationMessageInterceptor(
c =>
{
c.AcceptPublish = true;
});
mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMqttServer_ApplicationMessageReceived);
await mqttServer.StartAsync(optionsBuilder.Build());
toolStripLabel1.Text = "启动成功!";
}
}
catch (Exception ex)
{
toolStripLabel1.Text = "启动失败......";
}
}
public async void StopMqttServer()
{
if (mqttServer == null) return;
try
{
await mqttServer?.StopAsync();
mqttServer = null;
toolStripLabel1.Text = "关闭成功";
}
catch (Exception ex)
{
toolStripLabel1.Text = "关闭失败......";
}
}
private void button2_Click(object sender, EventArgs e)
{
ServerPublishMqttTopic();
}
public async void ServerPublishMqttTopic()
{
await mqttServer.SubscribeAsync(textBox4.Text);
label5.Text = textBox4.Text+"订阅成功!";
}
private void button3_Click(object sender, EventArgs e)
{
ServerPublishMqttTopic(textBox6.Text, textBox7.Text);
}
public async void ServerPublishMqttTopic(string topic, string payload)
{
var message = new MqttApplicationMessage()
{
Topic = topic,
Payload = Encoding.UTF8.GetBytes(payload)
};
await mqttServer.PublishAsync(message);
textBox5.Text = textBox5.Text + "主题:"+topic+"\n内容:"+payload+"\n发送成功!\n";
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
StopMqttServer();
}
public void OnMqttServerClientConnected(MqttServerClientConnectedEventArgs e)
{
lianjie++;
toolStripLabel2.Text = "连接数:" +lianjie;
}
public void OnMqttServerClientDisconnected(MqttServerClientDisconnectedEventArgs e)
{
lianjie--;
toolStripLabel2.Text = "连接数:" + lianjie;
}
public void OnMqttServer_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
string text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
string Topic = e.ApplicationMessage.Topic;
string QoS = e.ApplicationMessage.QualityOfServiceLevel.ToString();
string Retained = e.ApplicationMessage.Retain.ToString();
MyInvoke jieshou = new MyInvoke(jieshouo);
this.BeginInvoke(jieshou, new Object[] { Topic, QoS, Retained, text });
}
public void jieshouo(string strr1, string strr2, string strr3, string strr4)
{
textBox5.Text = textBox5.Text +"主题来源:"+ strr1 +"\nQoS:"+ strr2+"\nRetained:" + strr3+"\n内容:" + strr4+"\n----\n";
}
}
}
响应函数我没有全列出来,大家可以参考
https://blog.csdn.net/xiakexingtx/article/details/108281359
的文章自行添加动作函数
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
上面的
mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
大家多了解了解eventhandle就没问题了
下面来说一下具体的使用:
客户端具体的接入:
mqtt客户端需要接入的地址一共有四种(我们已经加了三个了,ip是第四个,不需要用户自定):
ip,端口,账号,密码
-----------------------------------------------------------------------------------------------
ip----
win+r——cmd——ipconfig里面的ipv4地址就是了(如果大家用emqx平台或者腾讯阿里的话请自行搞)
端口----
自行选择
账号----
自行选择
密码----
自行选择
-----------------------------------------------------------------------------------------------
我用来测试的客户端软件是MQTT.fx
目前的缺陷,客户端不能发送空内容,否则服务端程序会报错。
软件的教程百度上一大把我就不说了
好了,大部分都是前人的借鉴,只不过我来整理了一下。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现