public classMainViewModel : ViewModelBase
{///
///Initializes a new instance of the MainViewModel class.///
publicMainViewModel()
{
ClientInsTances= new ObservableCollection();
}
IMqttServer mqttServer; //MQTT服务端实例stringmessage;///
///消息 用于界面显示///
public stringMessage
{get { returnmessage; }set { message =value; RaisePropertyChanged(); }
}
ObservableCollectionclientInstances; //客户端登陆缓存信息///
///客户端实例///
public ObservableCollectionClientInsTances
{get { returnclientInstances; }set { clientInstances =value; RaisePropertyChanged(); }
}
//开启MQTT服务public voidOpenMqttServer()
{
mqttServer= newMqttFactory().CreateMqttServer();var options = newMqttServerOptions();//拦截登录
options.ConnectionValidator = c =>{try{
Message+= string.Format("用户尝试登录:用户ID:{0}用户信息:{1}用户密码:{2}", c.ClientId, c.Username, c.Password) + "";if (string.IsNullOrWhiteSpace(c.Username))
{
Message+= string.Format("用户:{0}登录失败,用户信息为空", c.ClientId) + "";
c.ReturnCode=MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;return;
}//解析用户名和密码,这个地方需要改成查找我们自己创建的用户名和密码。
if (c.Username == "admin" && c.Password == "123456")
{
c.ReturnCode=MqttConnectReturnCode.ConnectionAccepted;
Message+= c.ClientId + "登录成功" + "";
ClientInsTances.Add(newClientInstance()
{
ClientID=c.ClientId,
UserName=c.Username,
PassWord=c.Password
});return;
}else{
c.ReturnCode=MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
Message+= "用户名密码错误登陆失败" + "";return;
}
}catch(Exception ex)
{
Console.WriteLine("登录失败:" +ex.Message);
c.ReturnCode=MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;return;
}
};//拦截订阅
options.SubscriptionInterceptor = async context =>{try{
Message+= "用户" + context.ClientId + "订阅" + "";
}catch(Exception ex)
{
Console.WriteLine("订阅失败:" +ex.Message);
context.AcceptSubscription= false;
}
};//拦截消息
options.ApplicationMessageInterceptor = context =>{try{//一般不需要处理消息拦截//Console.WriteLine(Encoding.UTF8.GetString(context.ApplicationMessage.Payload));
}catch(Exception ex)
{
Console.WriteLine("消息拦截:" +ex.Message);
}
};
mqttServer.ClientDisconnected+=ClientDisconnected;
mqttServer.ClientConnected+=MqttServer_ClientConnected;
mqttServer.Started+=MqttServer_Started;
mqttServer.StartAsync(options);
}private void MqttServer_Started(objectsender, EventArgs e)
{
Message+= "消息服务启动成功:任意键退出" + "";
}private void MqttServer_ClientConnected(objectsender, MqttClientConnectedEventArgs e)
{//客户端链接
Message += e.ClientId + "连接" + "";
}private void ClientDisconnected(objectsender, MqttClientDisconnectedEventArgs e)
{//客户端断开
Message += e.ClientId + "断开" + "";
}///
///客户端推送信息 - 用于测试服务推送///
///
///
public void SendMessage(string clientID, stringmessage)
{
mqttServer.PublishAsync(newMqttApplicationMessage
{
Topic=clientID,
QualityOfServiceLevel=MqttQualityOfServiceLevel.ExactlyOnce,
Retain= false,
Payload=Encoding.UTF8.GetBytes(message),
});
}
}