MQTT服务(C#)
MQTT服务器(C#)
开启MQTT服务器,需要用到库MQTTnet
,使用VS2019企业版。
-
右键管理Nuget包,搜索下载
MQTTnet
(3.0.16版本)并安装,Install-Package MQTTNET
,出现下列提示,安装成功;Successfully installed 'MQTTnet 3.0.16' to MQTTNET
Executing nuget actions took 2.77 min
Time Elapsed: 00:02:46.6697077
========== Finished ==========
-
对C#代码添加
MQTTnet
和MQTTnet.Server
命名空间的引用; -
对构造函数里添加如下代码:
public MqttServer() { server = new MqttFactory().CreateMqttServer(); // 客户端连接事件 server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(ClientConnectedHandler); //客户端断开连接事件 server.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(ClientDisconnectedHandler); server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(MessageReceivedHandler); server.UseApplicationMessageReceivedHandler(args => { Console.WriteLine("==================================================="); Console.WriteLine("收到消息:"); Console.WriteLine($"客户端:{args.ClientId}"); Console.WriteLine($"主题:{args.ApplicationMessage.Topic}"); Console.WriteLine($"消息:{Encoding.UTF8.GetString(args.ApplicationMessage.Payload)}"); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(); }); } IMqttServer server;
-
开启关闭MQTT服务如下,调用
StartMqttServer
方法即可开启特定端口服务/// <summary> /// 打开MQTT Server 服务 /// </summary> /// <param name="port">端口号:默认为1883</param> public async void StartMqttServer(int port = 1883) { if (server.IsStarted) return; MqttServerOptionsBuilder serverOptions = new MqttServerOptionsBuilder(); serverOptions.WithDefaultEndpointPort(port); await server.StartAsync(serverOptions.Build()); } public async void CloseMqttServer(int port = 1883) { if (!server.IsStarted) return; MqttServerOptionsBuilder serverOptions = new MqttServerOptionsBuilder(); serverOptions.WithDefaultEndpointPort(port); await server.StopAsync(); }
-
其余调用方法如下:
private void StartedHandler(EventArgs obj) { Console.WriteLine("MQTT服务器已启动!"); } private void StoppedHandler(EventArgs obj) { Console.WriteLine("MQTT服务器已停止!"); } /// <summary> /// 客户端连接到服务器事件 /// </summary> /// <param name="obj"></param> private void ClientConnectedHandler(MqttServerClientConnectedEventArgs obj) { Console.WriteLine($"{obj.ClientId}此客户端已连接至服务器!"); } private void ClientDisconnectedHandler(MqttServerClientDisconnectedEventArgs obj) { Console.WriteLine($"断开连接的客户端:{obj.ClientId}"); Console.WriteLine($"断开连接类型:{obj.DisconnectType.ToString()}"); } /// <summary> /// 收到各个客户端发送的消息 /// </summary> /// <param name="obj"></param> private void MessageReceivedHandler(MqttApplicationMessageReceivedEventArgs obj) { Console.WriteLine("==================================================="); Console.WriteLine("收到消息:"); Console.WriteLine($"客户端:{obj.ClientId}"); Console.WriteLine($"主题:{obj.ApplicationMessage.Topic}"); Console.WriteLine($"消息:{Encoding.UTF8.GetString(obj.ApplicationMessage.Payload)}"); Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++++++"); Console.WriteLine(); }