c# - Azure物联网中心: Can't call direct method using AMQP protocol

标签 c# azure iot azure-iot-hub

我一直在尝试使用 AMQP 协议(protocol)进行直接方法调用。但无法使其发挥作用。我相信如果我没记错的话,可以通过 AMQP 调用直接方法。不过它可以与 MQTT 配合使用。任何线索将不胜感激。

代码如下:

using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace VirtualIoTDevice
{
    internal class Program
    {
        private const string DeviceConnectionString = "device-connection-string";
        private const string DEVICE_ID = "device01";
        private static DeviceClient _device;

        private static async Task Main(string[] args)
        {
            Console.WriteLine("Initializing virtual IoT device..");
            using (_device = DeviceClient.CreateFromConnectionString(DeviceConnectionString, DEVICE_ID))
            {
                await _device.OpenAsync();
                await _device.SetMethodHandlerAsync("showMessage", ShowMessage, null);

                Console.ReadKey();
            }
        }

        private static Task<MethodResponse> ShowMessage(MethodRequest methodRequest, object userContext)
        {
            Console.WriteLine("***Direct message received***");
            Console.WriteLine(methodRequest.DataAsJson);

            var responsePayload = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(new { response = "Message shown!" }));
            return Task.FromResult(new MethodResponse(responsePayload, 200));
        }
    }
}

这是调用直接方法的命令:

az iot hub invoke-device-method -n "iothub-name" -d "device01" --method-name "showMessage"

最佳答案

好的,我知道您的问题是什么:在最新版本的 SDK 中,阻塞线程方面发生了一些变化。我不知道这是有意的改变还是回归。

但是,在您的情况下,Console.ReadKey() 首先以某种方式阻止 AMQP 连接。 MQTT 不受此影响 - 这可能表明它可能是一种回归。

因此,如果您将 Console.ReadKey() 更改为 await Task.Delay(-1),它在我的测试中会再次起作用。

关于c# - Azure物联网中心: Can't call direct method using AMQP protocol,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759059/

相关文章:

python - 检查python是否安装

Python将数据保存到PostgreSQL : array value error

mqtt - 横向扩展 mosquitto 代理

C# 从另一个类中设置并从另一个类中获取

c# - 在什么情况下 GetType() 方法将返回接口(interface)的类型

.net - Azure 在哪个 IIS 版本上运行?

azure - 在 azure 函数核心工具中模拟 blob 存储绑定(bind)

c - for 循环中的 AT 命令

linux - 从技术角度了解物联网系统的架构

c# - 在 C# 中不使用 ODBC.DataReader 将数据传递给另一个类