简体   繁体   English

接收来自Azure Servicebus / IotHub的消息

[英]Receive messages from Azure Servicebus / IotHub

I want to check the azure servicebus/iothub constantly for messages. 我想不断检查azure servicebus / iothub中是否有消息。 However, when I do it like this I get the following error 但是,当我这样做时,出现以下错误

"An exception of type 'Amqp.AmqpException' occurred in mscorlib.dll but was not handled in user code Additional information: Operation 'Receive' is not valid under state: End." “ mscorlib.dll中发生了'Amqp.AmqpException类型的异常,但未在用户代码中处理。其他信息:在状态:结束下,'接收'操作无效。”

Any ideas how I should implement constant pulling of messages and/or resolve this error? 有什么想法我应该如何实现消息的不断提取和/或解决此错误?

var connection = new Connection(address);
var session = new Session(connection);
var entity = Fx.Format("/devices/{0}/messages/deviceBound", _deviceId);

var receiveLink = new ReceiverLink(session, "receive-link", entity);
while (true)
{
    await Task.Delay(1000);

    var message = await receiveLink.ReceiveAsync();
    if (message == null) continue;
    //else do things with message
 }

From the endpoint you're using it looks like you're talking about receiving cloud-to-device (c2d) messages, in other words, the code you're writing runs on the device, and is meant to receive messages sent through the service to this device, right? 从您正在使用的端点看,您正在谈论接收云到设备(c2d)消息,换句话说,您正在编写的代码在设备上运行,并且旨在接收通过服务于此设备,对吗?

The simplest way of doing this is using the DeviceClient class of the C# SDK . 最简单的方法是使用C#SDKDeviceClient类。 An example of how to use this class is provided in the DeviceClientAmqpSample project. DeviceClientAmqpSample项目中提供了有关如何使用此类的示例

Once you create your DeviceClient instance using your device connection string, the DeviceClient class has a ReceiveAsync method that can be used to receive messages. 使用设备连接字符串创建DeviceClient实例后, DeviceClient类将具有一个ReceiveAsync方法,该方法可用于接收消息。

var deviceClient = DeviceClient.CreateFromConnectionString("<DeviceConnectionString>");
while(true)
{
    await Task.Delay(1000);
    var receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
    if (receivedMessage != null)
    {
        var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
        Console.WriteLine("\t{0}> Received message: {1}", DateTime.Now.ToLocalTime(), messageData);
        await deviceClient.CompleteAsync(receivedMessage);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM