.Net6 控制台服务端 MQTTnet(3.1.1)
安装个MQTTnet 3.1.1,然后开干
不废话了,直接贴代码
public class Program
{
public static IMqttServer mqttServer;
static void Main(string[] args)
{
StartServer();
while (true)
{
var inputString = Console.ReadLine().ToLower().Trim();
if (inputString == "exit")
{
mqttServer?.StopAsync();
Console.WriteLine("MQTT服务已停止!"); break;
}
else if (inputString == "clients")
{
Console.ForegroundColor = ConsoleColor.White;
foreach (var item in mqttServer.GetClientStatusAsync().Result)
{
Console.WriteLine($"客户端标识:{item.ClientId},协议版本:{item.ProtocolVersion}");
}
Console.WriteLine($"在线客户端数量: {mqttServer.GetClientStatusAsync().Result.Count}");
}
else
{
Console.WriteLine($"命令[{inputString}]无效!");
}
}
}
//启动Mqtt服务器
private static async void StartServer()
{
try
{
//验证客户端信息
var options = new MqttServerOptions
{
//连接验证
ConnectionValidator = new MqttServerConnectionValidatorDelegate(p =>
{
if (p.Username.ToLower() != "admin" || p.Password.ToLower() != "admin")
{
p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
}
})
};
//设置端口号
options.DefaultEndpointOptions.Port = 1883;
options.DefaultEndpointOptions.ConnectionBacklog = 150;
//创建Mqtt服务器
mqttServer = new MqttFactory().CreateMqttServer();
//订阅事件
mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedTopicHandlerDelegate(MqttServer_SubscribedTopic);
//取消订阅事件
mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(MqttServer_UnSubscribedTopic);
//客户端消息事件
mqttServer.UseApplicationMessageReceivedHandler(MqttServer_ApplicationMessageReceived);
//客户端连接事件
mqttServer.UseClientConnectedHandler(MqttServer_ClientConnected);
//客户端断开事件
mqttServer.UseClientDisconnectedHandler(MqttServer_ClientDisConnected);
//启动服务器
await mqttServer.StartAsync(options);
}
catch (Exception e)
{
Console.Write($"服务器启动失败 Msg:{e.Message}");
}
}
/// <summary>
/// 客户订阅
/// </summary>
private static void MqttServer_SubscribedTopic(MqttServerClientSubscribedTopicEventArgs e)
{
//客户端Id
var ClientId = e.ClientId;
var Topic = e.TopicFilter.Topic;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine($"客户端[{ClientId}]已订阅主题:{Topic}");
}
/// <summary>
/// 客户取消订阅
/// </summary>
private static void MqttServer_UnSubscribedTopic(MqttServerClientUnsubscribedTopicEventArgs e)
{
//客户端Id
var ClientId = e.ClientId;
var Topic = e.TopicFilter;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine($"客户端[{ClientId}]已取消订阅主题:{Topic}");
}
/// <summary>
/// 接收消息
/// </summary>
private static void MqttServer_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
if (e.ApplicationMessage.Topic.Equals("topic01"))
{
try
{
string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
// 然后就处理信息就好了 payload
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
/// <summary>
/// 客户连接
/// </summary>
private static void MqttServer_ClientConnected(MqttServerClientConnectedEventArgs e)
{
var ClientId = e.ClientId;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"客户端[{ClientId}]已连接");
}
/// <summary>
/// 客户连接断开
/// </summary>
private static void MqttServer_ClientDisConnected(MqttServerClientDisconnectedEventArgs e)
{
var ClientId = e.ClientId;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"客户端[{ClientId}]已断开连接");
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律