我得到「AMQP:未經授權的訪問」錯誤,由於不發送把令牌消息:
string sasToken = GetSharedAccessSignature(null, device_key, resourceUri, new TimeSpan(1, 0, 0));
bool cbs = PutCbsToken(connection, host, sasToken, audience);
我的Windows 10桌面上測試用下面的代碼,它適用於發送和接收:
static string host = "[IOT_HUB_NAME].azure-devices.net";
static int port = 5671;
static string device_id = "[DEVICE_ID]";
static string device_key = "[DEVICE_KEY]";
static Session session;
static void Main(string[] args)
{
Address address = new Address(host, port, null, null);
Connection connection = new Connection(address);
string audience = Fx.Format("{0}/devices/{1}", host, device_id);
string resourceUri = Fx.Format("{0}/devices/{1}", host, device_id);
string sasToken = GetSharedAccessSignature(null, device_key, resourceUri, new TimeSpan(1, 0, 0));
bool cbs = PutCbsToken(connection, host, sasToken, audience);
session = new Session(connection);
SendEvent();
ReceiveCommands();
Console.ReadLine();
}
static private void SendEvent()
{
string entity = Fx.Format("/devices/{0}/messages/events", device_id);
SenderLink senderLink = new SenderLink(session, "sender-link", entity);
var messageValue = Encoding.UTF8.GetBytes("i am a message.");
Message message = new Message()
{
BodySection = new Data() { Binary = messageValue }
};
senderLink.Send(message);
senderLink.Close();
}
static private void ReceiveCommands()
{
string entity = Fx.Format("/devices/{0}/messages/deviceBound", device_id);
ReceiverLink receiveLink = new ReceiverLink(session, "receive-link", entity);
Message received = receiveLink.Receive();
if (received != null)
receiveLink.Accept(received);
Console.WriteLine(received.BodySection.ToString());
receiveLink.Close();
}
欲瞭解更多信息,你可以參考「CONNECTING TO THE AZURE IOT HUB USING AN AMQP STACK」。
更新:
代替使用SAS令牌像上面的代碼塊,下面的代碼使用共享訪問策略和密鑰(SASL PLAIN)的:
static string host = "[IOT_HUB_NAME].azure-devices.net";
static int port = 5671;
static string device_id = "[DEVICE_ID]";
static string device_key = "[DEVICE_KEY]";
private const string username_hublevel = "[email protected][IOT_HUB_NAME]";
private const string password_hublevel = "SharedAccessSignature sr={URL-encoded-resourceURI}&sig={signature-string}&se={expiry}&skn={policyName}";
static Session session;
static void Main(string[] args)
{
Address address = new Address(host, port, username_hublevel, password_hublevel);
Connection connection = new Connection(address);
string audience = Fx.Format("{0}/devices/{1}", host, device_id);
string resourceUri = Fx.Format("{0}/devices/{1}", host, device_id);
session = new Session(connection);
SendEvent();
Console.WriteLine("Sent Hello AMQP!");
ReceiveCommands();
Console.ReadLine();
}
>在每次請求生成SAS令牌是多餘的。只需指出,您不必爲每個請求生成新的SAS令牌。 – bearrito