用本地C#写出的WebService利用MQTT协议去连接阿里云来实现数值的远程传输和使用(同步调用)第一篇:搭建WebService

创建项目

  1.启动vs2017并新建一个项目,如下图所示:
在这里插入图片描述
  2.建立一个空项目
在这里插入图片描述
  3.添加一个asmx文件
在这里插入图片描述
在这里插入图片描述
  记住创建的文件的名字!之后发布的时候要用到!
  然后将下列代码直接复制进VS当中:(注:还得像之前那样装载一次MQTT库,不知道怎么装MQTT库的,可以去我以前的这篇文章查看 https://blog.csdn.net/qq_19408097/article/details/96346936 )
  这段代码的大致解读在我以前的一篇文章里已经解读过了,想要了解的可以去 https://blog.csdn.net/qq_19408097/article/details/96425940 了解一下。

using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Security.Cryptography;
using System.Web;
using System.Web.Services;
using System.Threading;
using shuju;
namespace _1
{
    /// <summary>
    /// _1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]//发布前最好改下这个namespace
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class _1 : System.Web.Services.WebService
    {
        //阿里云的数据
        //System.Threading.Thread a = new System.Threading.Thread();
        static string ProductKey = "***";//输入自己设备的productkey
        static string DeviceName = "***";//输入自己设备的devicename
        static string DeviceSecret = "***";//输入自己设备的devicename
        static string RegionId = "***";//输入自己设备的regionid
        static string PubTopic = "/" + ProductKey + "/" + DeviceName + "/user/update";
        static string SubTopic = "/" + ProductKey + "/" + DeviceName + "/user/get";

        //声明一个委托
        delegate string LongCalculationDelegate(int a);
        [WebMethod(Description = "阿里云")]
        public string (int a)//主程序
        {
            LongCalculationDelegate b = new LongCalculationDelegate(xiancheng);
            string x=b.Invoke(a);
            //x = common.Name;
            return x;
        }
        static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // handle message received
            string topic = e.Topic;
            string message = Encoding.ASCII.GetString(e.Message);
            common.Name = message;
        }
        static string xiancheng(int a)
        {
            //开始连接阿里云
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            string clientId = host.AddressList.FirstOrDefault(
                ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();
            string t = Convert.ToString(DateTimeOffset.Now.ToUnixTimeMilliseconds());
            string signmethod = "hmacmd5";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("productKey", ProductKey);
            dict.Add("deviceName", DeviceName);
            dict.Add("clientId", clientId);
            dict.Add("timestamp", t);
            string mqttUserName = DeviceName + "&" + ProductKey;
            string mqttPassword = IotSignUtils.sign(dict, DeviceSecret, signmethod);
            string mqttClientId = clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + t + "|";
            string targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";
            MqttClient client = new MqttClient(targetServer);
            client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
            client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60);
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            //发布消息
            String content = Convert.ToString(a);
            //将string类转换成byte[]
            byte[] by1 = System.Text.Encoding.ASCII.GetBytes(content);
            var id = client.Publish(PubTopic, by1);
            //订阅消息

            var id2 = client.Subscribe(new string[] { SubTopic }, new byte[] { 0 });
        lop:
            if (string.Compare(common.Name, " ") == 0)
                goto lop;
           else
            {
            loop:
                if (string.Compare(common.Name, Convert.ToString(a)) != 0)
                    goto loop;
                else
                    return common.Name;
            }
        }
    }
    public class IotSignUtils//IoT平台接入password签名算法
    {
        public static string sign(Dictionary<string, string> param,
                            string deviceSecret, string signMethod)
        {
            string[] sortedKey = param.Keys.ToArray();
            Array.Sort(sortedKey);
            StringBuilder builder = new StringBuilder();
            foreach (var i in sortedKey)
            {
                builder.Append(i).Append(param[i]);
            }

            byte[] key = Encoding.UTF8.GetBytes(deviceSecret);
            byte[] signContent = Encoding.UTF8.GetBytes(builder.ToString());
            var hmac = new HMACMD5(key);
            byte[] hashBytes = hmac.ComputeHash(signContent);

            StringBuilder signBuilder = new StringBuilder();
            foreach (byte b in hashBytes)
                signBuilder.AppendFormat("{0:x2}", b);
            return signBuilder.ToString();
        }
    }
}

  但这个时候程序还是会出现错误,因为shuju这个类我还没有建立。所以我们现在就要建立一个common类,他的作用就类似于C语言里面的全局变量(人造)。
  按下ctrl+shift+A进行页面的添加。选择如下该项。
在这里插入图片描述
建立完成以后,将下列代码拷入:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace shuju
{
    public static class common
    {
        private static string name = " ";
        public static string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
}

程序运行一下以后,就能看见如下界面,然后点击“值”:在这里插入图片描述
在这里进行值的输入:
在这里插入图片描述
输入完成以后,点击调用:
在这里插入图片描述
  然后我们可以进入阿里云端日志服务进行查看,发现数据已经上传到了阿里云然后由阿里云通过下行数据回传回来了:
在这里插入图片描述
在这里插入图片描述
  但是现在还是有点小的问题,那就是这个网站我们还没有发布,所以别的程序是没有办法去引用这个webservice的,下一篇我会讲的就是如何发布这个网站,本篇到这里就结束了,谢谢大家。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值