简体   繁体   中英

Receive messages from Azure Servicebus / IotHub

I want to check the azure servicebus/iothub constantly for messages. 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."

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?

The simplest way of doing this is using the DeviceClient class of the C# SDK . An example of how to use this class is provided in the DeviceClientAmqpSample project.

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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