c#实现mqtt服务端与客户端通讯功能-kb88凯时官网登录

来自:网络
时间:2023-01-01
阅读:
免费资源网 - https://freexyz.cn/

关于mqtt

mqtt(消息队列遥测传输)是iso 标准(iso/iec prf 20922)下基于发布/订阅范式的消息协议。它工作在 tcp/ip协议族上,是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅型消息协议,为此,它需要一个消息中间件 。

mqtt是一个基于客户端-服务器的消息发布/订阅传输协议。mqtt协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(m2m)通信和物联网(iot)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

mqtt示例

注: 该示例演示统一使用wpf, 简单mvvm模式演示, 复制代码需注意引用 nuget包 galasoft

mqtt服务端建立:

演示界面:

演示代码:

public class mainviewmodel : viewmodelbase
    {
        /// 
        /// initializes a new instance of the mainviewmodel class.
        /// 
        public mainviewmodel()
        {
            clientinstances = new observablecollection();
        }
        imqttserver mqttserver;  //mqtt服务端实例
        string message; 
        /// 
        /// 消息   用于界面显示
        /// 
        public string message
        {
            get { return message; }
            set { message = value; raisepropertychanged(); }
        }
        observablecollection clientinstances; //客户端登陆缓存信息
        /// 
        /// 客户端实例
        /// 
        public observablecollection clientinstances
        {
            get { return clientinstances; }
            set { clientinstances = value; raisepropertychanged(); }
        }
     //开启mqtt服务
        public void openmqttserver()
        {
            mqttserver = new mqttfactory().createmqttserver();
            var options = new mqttserveroptions();
            //拦截登录
            options.connectionvalidator = c =>
            {
                try
                {
                    message  = string.format("用户尝试登录:用户id:{0}\t用户信息:{1}\t用户密码:{2}", c.clientid, c.username, c.password)   "\r\n";
                    if (string.isnullorwhitespace(c.username))
                    {
                        message  = string.format("用户:{0}登录失败,用户信息为空", c.clientid)   "\r\n";
                        c.returncode = mqttnet.protocol.mqttconnectreturncode.connectionrefusedbadusernameorpassword;
                        return;
                    }
                    //解析用户名和密码,这个地方需要改成查找我们自己创建的用户名和密码。
                    if (c.username == "admin" && c.password == "123456")
                    {
                        c.returncode = mqttconnectreturncode.connectionaccepted;
                        message  = c.clientid   " 登录成功"   "\r\n";
                        clientinstances.add(new clientinstance()
                        {
                            clientid = c.clientid,
                            username = c.username,
                            password = c.password
                        });
                        return;
                    }
                    else
                    {
                        c.returncode = mqttconnectreturncode.connectionrefusedbadusernameorpassword;
                        message  = "用户名密码错误登陆失败"   "\r\n";
                        return;
                    }
                }
                catch (exception ex)
                {
                    console.writeline("登录失败:"   ex.message);
                    c.returncode = mqttconnectreturncode.connectionrefusedidentifierrejected;
                    return;
                }
            };
            //拦截订阅
            options.subscriptioninterceptor = async context =>
            {
                try
                {
                    message  = "用户"   context.clientid   "订阅"   "\r\n";
                }
                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(object sender, eventargs e)
        {
            message  = "消息服务启动成功:任意键退出"   "\r\n";
        }
        private void mqttserver_clientconnected(object sender, mqttclientconnectedeventargs e)
        {
            //客户端链接
            message  = e.clientid   "连接"   "\r\n";
        }
        private void clientdisconnected(object sender, mqttclientdisconnectedeventargs e)
        {
            //客户端断开
            message  = e.clientid   "断开"   "\r\n";
        }
        /// 
        /// 客户端推送信息    -  用于测试服务推送
        /// 
        /// 
        /// 
        public void sendmessage(string clientid, string message)
        {
            mqttserver.publishasync(new mqttapplicationmessage
            {
                topic = clientid,
                qualityofservicelevel = mqttqualityofservicelevel.exactlyonce,
                retain = false,
                payload = encoding.utf8.getbytes(message),
            });
        }
    }

添加mqtt 客户端登陆实例, 用于保存客户的登陆信息,如下:

演示界面:

    /// 
    /// 登陆客户端信息
    /// 
    public class clientinstance : viewmodelbase
    {
        private string clientid;
        private string username;
        private string password;
        /// 
        /// 识别id
        /// 
        public string clientid
        {
            get { return clientid; }
            set { clientid = value; raisepropertychanged(); }
        }
        /// 
        /// 账户
        /// 
        public string username
        {
            get { return username; }
            set { username = value; raisepropertychanged(); }
        }
        /// 
        /// 密码
        /// 
        public string password
        {
            get { return password; }
            set { password = value; raisepropertychanged(); }
        }
    }

mqtt客户端建立:

演示代码:

public class mainviewmodel : viewmodelbase
    {
        /// 
        /// initializes a new instance of the mainviewmodel class.
        /// 
        public mainviewmodel()
        {
            clientid = new random().next(999, 9999)   ""; //测试随机生成clientid
        }
        imqttclient mqttclient;  //mqtt客户端实例
        string clientid; //机器id
        string message;
        public string message  //用于接收当前 消息
        {
            get { return message; }
            set { message = value; raisepropertychanged(); }
        }
        //开启mqtt连接
        public async void signmqttserver()
        {
            var options = new mqttclientoptionsbuilder()
             .withclientid(clientid) //传递clientid 
             .withtcpserver("127.0.0.1", 1883)  //mqtt服务的地址
             .withcredentials("admin", "123456") //传递账号密码
             .withcleansession()
             .build();
            mqttclient = new mqttfactory().createmqttclient();// .createmanagedmqttclient();
            mqttclient.connected  = mqttclient_connected;
            mqttclient.disconnected  = mqttclient_disconnected;
            mqttclient.applicationmessagereceived  = mqttclient_applicationmessagereceived; //创建消息接受事件
            await mqttclient.connectasync(options);
            //await mqttclient.subscribeasync(clientid);
        }
        private void mqttclient_applicationmessagereceived(object sender, mqttapplicationmessagereceivedeventargs e)
        {
            message  = "收到的信息:"   encoding.utf8.getstring(e.applicationmessage.payload)   "\r\n";
        }
        private void mqttclient_disconnected(object sender, mqttclientdisconnectedeventargs e)
        {
            message  = "客户端断开";
        }
        private void mqttclient_connected(object sender, mqttclientconnectedeventargs e)
        {
            message  = "客户端已连接"   "\r\n";
            mqttclient.subscribeasync(new topicfilterbuilder().withtopic(clientid).build()); //关联服务端订阅, 用于接受服务端推送信息
        }
    }

演示界面:

实际演示效果(gif)

到此这篇关于c#实现mqtt服务端与客户端通讯功能的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

免费资源网 - https://freexyz.cn/
返回顶部
顶部
网站地图