工业互联-基于C#的MQTT服务器开发

安装MQTTnet包,这我用的版本是3.1.2

public static IMqttServer server = null;

基于C#的MQTT服务器开发:

 1         /// <summary>
 2         /// 开启mqtt服务
 3         /// </summary>
 4         private static async void ServerStart()
 5         {
 6             server = new MqttFactory().CreateMqttServer();
 7             // 初始化Sever对象
 8             server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(Server_ClientConnected);
 9             server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(Server_ClientSubscribedTopic);
10             server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(Server_ApplicationMessageReceived);
11             MqttServerOptionsBuilder msob = new MqttServerOptionsBuilder()
12                 .WithDefaultEndpointBoundIPAddress(IPAddress.Any) // 任意ip地址,相当于0.0.0.0
13                 .WithDefaultEndpointPort(1121)// 客户端连接服务器如果使用其他端口号,无法连接
14                 .WithConnectionValidator(ConnectionValidator); // 匹配客户端设置用户名和密码
15             IMqttServerOptions serverOptions = msob.Build(); // 配置对象生成
16             await server.StartAsync(serverOptions); // 根据配置信息启动服务器
17             Console.WriteLine("MQTT服务端已启动完成!");
18         }
19 
20         /// <summary>
21         /// 用户名和密码匹配
22         /// </summary>
23         /// <param name="context"></param>
24         private static void ConnectionValidator(MqttConnectionValidatorContext context)
25         {
26             if (context.Username != "admin" || context.Password != "123456")
27             {
28                 context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
29             }
30             context.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;
31         }
32 
33         /// <summary>
34         /// topic,订阅消息
35         /// </summary>
36         /// <param name="e"></param>
37         private static void Server_ClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs e)
38         {
39             Console.WriteLine(">>> 客户端:" + e.ClientId + "  订阅topic:" + e.TopicFilter.Topic);
40         }
41 
42         /// <summary>
43         /// 客户端连接服务器
44         /// </summary>
45         /// <param name="e"></param>
46         private static void Server_ClientConnected(MqttServerClientConnectedEventArgs e)
47         {
48             Console.WriteLine(">>> 客户端:" + e.ClientId + " 连接");
49         }
50 
51         /// <summary>
52         /// 客户端接收消息
53         /// </summary>
54         /// <param name="e"></param>
55         private static void Server_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
56         {
57             if (e.ClientId != null)
58             {
59                 ushort value = BitConverter.ToUInt16(new byte[] { e.ApplicationMessage.Payload[1],e.ApplicationMessage.Payload[0] });
60                 Console.WriteLine(value);
61                 // 接收从客户端发到服务器的消息,将这个消息分发下去
62                 Console.WriteLine(">>> 收到消息:" + e.ApplicationMessage.ConvertPayloadToString() + ",来自客户端" + e.ClientId + ",topic:" + e.ApplicationMessage.Topic);
63                 // 将客户端发过来的消息,根据topic进行分发
64                 server.PublishAsync(e.ApplicationMessage);
65             }
66         }
View Code

服务端监听:

客户端连接mqtt服务器端:

 

客户端1发送消息给客户端2:

 

posted @ 2023-08-11 21:57  逆风起降  阅读(37)  评论(0编辑  收藏  举报