服务端:
using MQTTnet;
using MQTTnet.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace MQTTNetService
{
public partial class MQTTNetService : ServiceBase
{
private MqttServer mqttServer = null;
private System.Timers.Timer timer = null;
//此集合用于判断写入日志在一段时间内不重,以客户端id为依据,最多1000个清零;
private List subClientIDs = new List();
public MQTTNetService()
{
InitializeComponent();
//创建一个定时器,检查5s内有多少客户端接入并将相关信息记录到日志中
timer = new System.Timers.Timer();
timer.AutoReset = true;
timer.Enabled = true;
timer.Interval = 5000;
timer.Elapsed += new ElapsedEventHandler(GetSubClientSAndSetShow);
}
protected override void OnStart(string[] args)
{
//开启服务
CreateMQTTServer();
if (timer.Enabled == false)
{
timer.Enabled = true;
timer.Start();
}
}
protected override void OnStop()
{
if (timer.Enabled == true)
{
timer.Enabled = false;
timer.Stop();
}
}
///
/// 开启服务
///
private async void CreateMQTTServer()
{
if (mqttServer == null)
{
var options = new MqttServerOptions();
var optionsBuilder = new MqttServerOptionsBuilder();
//指定 ip地址,默认为本地,但此方法不能使用ipaddress报错,有哪位大神帮解答,感激。
//options.WithDefaultEndpointBoundIPAddress(IPAddress.Parse(""))
//指定端口
optionsBuilder.WithDefaultEndpointPort(1883);
//连接记录数,默认 一般为2000
//optionsBuilder.WithConnectionBacklog(2000);
mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
//将发送的消息加到日志
mqttServer.ApplicationMessageReceived += (s, e) =>
{
string msg = @"发送消息的客户端id:" + e.ClientId + "\n"
+ "发送时间:" + DateTime.Now + "\n"
+ "发送消息的主题:" + e.ApplicationMessage.Topic + "\n"
+ "发送的消息内容:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0]) + "\n"
+ "--------------------------------------------------\n"
;
WriteMsgLog(msg);
};
await mqttServer.StartAsync(options);
}
}
#region 记录日志
///
/// 消息记录日志
///
///
private void WriteMsgLog(string msg)
{
//string path = &