<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="https://www.w3.org/2005/Atom" xmlns:sy="https://purl.org/rss/1.0/modules/syndication/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:content="https://purl.org/rss/1.0/modules/content/" xmlns:wfw="https://wellformedweb.org/CommentAPI/" xmlns:slash="https://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Zhiqing's Blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/zhiqing/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/zhiqing/feed.xml</link>
    <description />
    <lastBuildDate>Wed, 17 Apr 2019 03:28:56 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>How to use AMQP protocol in Browser (JavaScript)</title>
      <link>https://docs.microsoft.com/archive/blogs/zhiqing/how-to-use-amqp-protocol-in-browser-javascript</link>
      <pubDate>Tue, 28 Mar 2017 03:32:32 GMT</pubDate>
      <dc:creator><![CDATA[michaeljqzq]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/zhiqing/?p=1185</guid>
      <description><![CDATA[p {
line-height:2em;
}

In my previous 2 posts, Connect to Azure Event Hub in browser ( using...]]></description>
      <content:encoded><![CDATA[<style>
p {
line-height:2em;
}
</style>
In my previous 2 posts, <a href="https://blogs.msdn.microsoft.com/zhiqing/2017/03/16/connect-to-azure-event-hub-in-browser-using-amqp-over-websockets/" target="_blank">Connect to Azure Event Hub in browser ( using AMQP over WebSockets )</a> and <a href="https://blogs.msdn.microsoft.com/zhiqing/2017/03/14/connect-to-azure-iot-hub-in-browser-using-amqp-over-websockets/" target="_blank">Connect to Azure IoT Hub in browser ( using AMQP over WebSockets )</a>, I introduced the parameters needed to connect to IoT Hub and Event Hub. Since we chose to connect in front-end, so we have to find a JavaScript library for AMQP. However, it isn't quite easy to find one.

<a href="https://github.com/grs/rhea" target="_blank">rhea</a> is a reactive messaging library based on the AMQP protocol which meet our need.It is a NodeJS project, but it provides a browserify command in script. So all we have to do is to make a little changes.

1.In the type wrapper (types.js), it is designed for Node so it uses Buffer class in code. 
[javascript]
if (o instanceof Buffer) {
    return types.wrap_binary(o);
}
[/javascript]

The corresponding data structure in front-end JavaScript is ArrayBuffer. So here we make this code compatible with browser.

[javascript]
if (o instanceof Buffer || o instanceof ArrayBuffer) {
    return types.wrap_binary(o);
}
[/javascript]

2.The library doesn't implement disconnect method. So let's add one in container.js
[javascript]
Container.prototype.disconnect = function () {
    this.connection.close();
};
[/javascript]

Now let's try to browerify the project!
First we need to set dependency.In the terminal, point to project root folder, set the environment variable NODE_PATH to the parent folder of your rhea project. For example, my project folder is C:\Users\v-zhq\IoT\rhea then you will set NODE_PATH to C:\Users\v-zhq\IoT.
Then execute in project folder C:\Users\v-zhq\IoT\rhea:
<pre>npm run browserify</pre>

rhea.js get!
Then you can use example to test! Point to examples/websockets and start an HTTP server. Then visit https://localhost:8000, input websocket url.

client.html ( in line #31 I made a little change or client object can't be initialized )
[html]
&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;AMQP websockets example&lt;/title&gt;
  &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html;charset=utf-8&quot; /&gt;
  &lt;!-- This example was adapted from a chat example included in the
  excellent 'JavaScript: The Definitive Guide', by David Flanagan and
  published by O'Reilly. --&gt;
&lt;script src=&quot;rhea.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;input type=&quot;text&quot; id=&quot;request&quot; style=&quot;width:100%&quot;/&gt;
&lt;script&gt;
var server = prompt(&quot;Enter details of server to use&quot;, &quot;ws://localhost:5673&quot;);
var input = document.getElementById(&quot;request&quot;);
input.focus();

function append(txt) {
    var node = document.createTextNode(txt);
    var div = document.createElement(&quot;div&quot;);
    div.appendChild(node);
    document.body.insertBefore(div, input);
    input.scrollIntoView();
}
input.onchange = function() {
    sender.send({&quot;body&quot;:input.value});
    input.value = &quot;&quot;;
};

var client = new(require(&quot;rhea&quot;))();
client.on(&quot;message&quot;, function (context) {
    append(context.message.body);
});
var ws = client.websocket_connect(WebSocket);
var connection = client.connect({&quot;connection_details&quot;:ws(server, [&quot;AMQPWSB10&quot;]), &quot;reconnect&quot;:false});
connection.open_receiver(&quot;examples&quot;);
var sender = connection.open_sender(&quot;examples&quot;);

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

[/html]
]]></content:encoded>
    </item>
    <item>
      <title>使用MQTT协议往Android手机推送消息</title>
      <link>https://docs.microsoft.com/archive/blogs/zhiqing/%E4%BD%BF%E7%94%A8mqtt%E5%8D%8F%E8%AE%AE%E5%BE%80android%E6%89%8B%E6%9C%BA%E6%8E%A8%E9%80%81%E6%B6%88%E6%81%AF</link>
      <pubDate>Sun, 19 Mar 2017 06:39:07 GMT</pubDate>
      <dc:creator><![CDATA[michaeljqzq]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/zhiqing/?p=976</guid>
      <description><![CDATA[p...]]></description>
      <content:encoded><![CDATA[<style>
p {
margin-top:10px;
}
</style>
最近做了一些IoT相关的工作，对于MQTT协议用得比较多。MQTT诞生较早（1999年）但是一直不温不火，直到最近由于物联网的兴起，才由IBM在2013年将其提交到了OASIS规范中，从而在物联网的协议中占得一席之地。这个协议有着如下特点：

	<li>轻量化，消息头部采用二进制格式</li>
	<li>订阅/发布模式，这样非常适合于服务器推送</li>
	<li>可以对不同的话题采用不同的QoS（服务质量），可以在可靠性和复杂度之间取得平衡</li>

介于之前一直想做一个往自己Android手机上推送消息的小应用。但是因为某些网络环境的原因<del datetime="2017-03-15T13:34:13+00:00">你懂的</del>，Google为Android设计的推送机制在国内并不能很好的使用。如果使用类似于Rest API轮询的方式，对于移动设备来说过于耗费电量以及流量，并不是很好的方法。了解到有了MQTT这种轻量级的协议以后，发现完美契合这个推送消息的需求。于是赶紧试一试！

在整个流程中，需要3个点，分别是MQTT Broker,推送消息的client，以及接收消息的Android client。

1. MQTT Broker
就是一个接受订阅，接受并转发消息的服务器。我选择基于Node的项目<a href="https://github.com/mcollina/mosca" target="_blank">mosca</a>，由于我是独立使用，所以特别简单。
<pre>npm install mosca pino -g
mosca -v | pino</pre>

简直不要太方便！<img src="https://msdnshared.blob.core.windows.net/media/2016/12/70.png" alt="70" width="150" height="130" class="alignnone size-full wp-image-615" />

查看一下网络端口
<pre>tcp6       0      0 :::1883                 :::*                    LISTEN</pre>

好，已经默认监听在1883端口了。

2. 推送消息的client
就是要推送消息的消息源。这个还是用Node的<a href="https://www.npmjs.com/package/mqtt" target="_blank">MQTT</a>项目（Node的库真是好用哭）。
同样是两种用法，第一种独立使用：
<pre>npm install mqtt -g
mqtt sub -t 'topic' -h 'broker_url' -v
mqtt pub -t 'topic' -h 'broker_url' -m 'message'</pre>
第二种嵌入code：
[javascript]
var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://test.mosquitto.org')
 
client.on('connect', function () {
  client.subscribe('presence')
  client.publish('presence', 'Hello mqtt')
})
 
client.on('message', function (topic, message) {
  // message is Buffer 
  console.log(message.toString())
  client.end()
})
[/javascript]

3. 接收消息的Android client
这个比前两个找起来难度大点。在Play市场上搜索MQTT，试了一些排名靠前的应用，发现对于MQTT的支持都没有什么问题，收发消息也都正常。但是都无法支持后台保持连接以及消息提醒机制。最后找到了这么一个应用，可以实现MQTT消息的后台以及息屏提醒，叫做<a href="https://play.google.com/store/apps/details?id=com.ravendmaster.linearmqttdashboard" target="_blank">Linear MQTT Dashboard</a>

打开应用 先进行一下简单的设置
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/149-599x1024.png" alt="1" width="300" height="512" class="alignnone size-large wp-image-1065" />

返回到主界面，可以看到有两个状态指示灯
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/234-599x1024.png" alt="2" width="300" height="512" class="alignnone size-large wp-image-1075" />
第二个就表示MQTT Broker的连接状态，如果是绿色的就说明已经成功连接上了。

然后增加一个widget来显示消息，先按一下上图中的暂停按钮，然后按加号添加一个widget，其中主要填好Sub.topic就可以了

我们试着从另一个地方往test话题推送一条消息
<pre>
mqtt pub -t 'test' -h '[MQTT_BROKER_URL]' -m 'hello world'
</pre>
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/323-599x1024.png" alt="3" width="300" height="512" class="alignnone size-large wp-image-1085" />
接收成功，那么看看如果app切到后台能不能收到提醒呢
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/48-300x266.jpg" alt="4" width="300" height="266" class="alignnone size-medium wp-image-1095" />
可以看到，成功在通知栏提醒了消息，并且有震动。在息屏时也会有震动提醒，完美！

那么到此为止，就利用MQTT协议成功的进行了从任意client往Android手机推送消息的机制，而且非常省电和省流量。其实在这个方案中，Android手机不仅可以作为消息的接收端，也可以作为消息的发送端，那么如果把接收端放在一些嵌入式设备或者小型开发板上（由于MQTT是物联网的标准协议，所以支持较为广泛），那么就可以通过手机来控制这些设备，进而实现智能家居等等任何你能想象的功能！]]></content:encoded>
    </item>
    <item>
      <title>Connect to Azure Event Hub in browser ( using AMQP over WebSockets )</title>
      <link>https://docs.microsoft.com/archive/blogs/zhiqing/connect-to-azure-event-hub-in-browser-using-amqp-over-websockets</link>
      <pubDate>Thu, 16 Mar 2017 12:52:45 GMT</pubDate>
      <dc:creator><![CDATA[michaeljqzq]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/zhiqing/?p=985</guid>
      <description><![CDATA[div.single > * {
margin-bottom: 15px;
}
#customers {
    font-family: Arial, Helvetica,...]]></description>
      <content:encoded><![CDATA[<style>
div.single > * {
margin-bottom: 15px;
}
#customers {
    font-family: Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
}
#customers td, #customers th {
    border: 1px solid #ddd;
    padding: 8px;
}#customers tr:nth-child(even){background-color: #f2f2f2;}#customers tr:hover {background-color: #ddd;}#customers th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: grey;
    color: white;
}
</style>

In my last post, I introduced the way to connect to Azure IoT Hub using AMQP over WebSockets. At the end of post, I said through this way we can only send C2D message to devices. However, open receiver to topic:/messages/serviceBound/feedback won't get any message when device send D2C message. So here's the problem, how to receive D2C message?

The answer is: Event Hub. You may ask, why can we get IoT Hub message through Event Hub? If you are familiar to Azure IoT Hub, you may find there's a "compatible" Event Hub in IoT Hub portal:
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_200532-1024x510.png" alt="snipaste_20170316_200532" width="1024" height="510" class="alignnone size-large wp-image-995" />
You may guess that IoT Hub is based on Event Hub? I had the same inference, but after contacting Azure suppport, they told me IoT Hub doesn't based on Event Hub.However, since IoT Hub are similar to Event Hub in many ways(both have message queue and handler), Azure provides a compatible way to visit IoT Hub as an Event Hub.So IoT Hub is not based on Event Hub, but compatible with Event Hub.
So now we can focus on how to fetch message from Event Hub.Let's go!

First, we must establish a websocket channel.
<pre>
wss://[EventHubEndpoint]:443/$servicebus/websocket
Sec-WebSocket-Protocol: AMQPWSB10
</pre>
<button id="b1" class="btn btn-info" onclick="$('#p1').slideDown();$('#b1').fadeOut();">How to get Event Hub Endpoint?</button>
<p id="p1" style="display: none; padding-left: 30px;">You can find it in Azure portal.<img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_201700-1024x509.png" alt="snipaste_20170316_201700" width="1024" height="509" class="alignnone size-large wp-image-1005" /></p>
Then you will have to establish AMQP connection. Use the following parameters to connect, you need to use SASL.
<table id="customers">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>hostname</td>
<td>[EventHubEndpoint]</td>
</tr>
<tr>
<td>container_id</td>
<td>"conn" + &lt;CURRENT-TIME-STAMP&gt;</td>
</tr>
<tr>
<td>max_frame_size</td>
<td>4294967295</td>
</tr>
<tr>
<td>channel_max</td>
<td>65535</td>
</tr>
<tr>
<td>idle_timeout</td>
<td>120000</td>
</tr>
<tr>
<td>outgoing_locales</td>
<td>en-US</td>
</tr>
<tr>
<td>incoming_locales</td>
<td>en-US</td>
</tr>
<tr>
<td>offered_capabilities</td>
<td>null</td>
</tr>
<tr>
<td>desired_capabilities</td>
<td>null</td>
</tr>
<tr>
<td>properties</td>
<td>{}</td>
</tr>
<tr>
<td>connection_details</td>
<td>&lt;YOUR-WEBSOCKET-CONNECTION&gt;</td>
</tr>
<tr>
<td>reconnect</td>
<td>false</td>
</tr>
<tr>
<td>username</td>
<td>[accessPolicyName]</td>
</tr>
<tr>
<td>password</td>
<td>[sharedAccessKey]</td>
</tr>
</tbody>
</table>
<button id="b2" class="btn btn-info" onclick="$('#p2').slideDown();$('#b2').fadeOut();">How to get Access Policy Name and Shared Access Key?</button>
<p id="p2" style="display: none; padding-left: 30px;">You can find it in Azure portal.<img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_202829-1024x507.png" alt="snipaste_20170316_202829" width="1024" height="507" class="alignnone size-large wp-image-1015" /></p>

After connection opened, we will open receiver on all partitions in Event Hub. How do we get all partition ids in Event Hub? 
We create a sender and a receiver on topic: <pre>$management</pre>
And then we will send a message on topic $management:
<pre>
body:'[]',
                application_properties: { 
                    operation: 'READ',
                    name: [EventHubPath],
                    type: 'com.microsoft:eventhub' 
                } 
</pre>
<button id="b3" class="btn btn-info" onclick="$('#p3').slideDown();$('#b3').fadeOut();">How to get Event Hub Path?</button>
<p id="p3" style="display: none; padding-left: 30px;">You can find it in Azure portal.<img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_203512-1024x503.png" alt="snipaste_20170316_203512" width="1024" height="503" class="alignnone size-large wp-image-1025" /></p>
Then we will receive a meesage with partition info:
<pre>
partition_count:2,
partition_ids:[0,1]
</pre>
Then we will open several receivers to fetch message.( The number of receivers equals to partition count ）
<pre>
/[eventHubPath]/ConsumerGroups/[consumerGroup]/Partitions/[partitionId]
</pre>
<button id="b4" class="btn btn-info" onclick="$('#p4').slideDown();$('#b4').fadeOut();">How to get Consumer Group?</button>
<p id="p4" style="display: none; padding-left: 30px;">You can find it in Azure portal.<img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_204025-1024x506.png" alt="snipaste_20170316_204025" width="1024" height="506" class="alignnone size-large wp-image-1035" /></p>

That's all for the work! <a href="https://blogs.msdn.microsoft.com/zheli/" target="_blank">Sneezry</a> and I just finished a <a href="https://iotdevtool.com/" target="_blank">Web Project</a> including Device/Service/Registry(device management).If you feel a bit confusion about the complicated process above, you can try this tool and it will provide you a easy-access experience to Azure IoT Hub!
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_204949-1024x391.png" alt="snipaste_20170316_204949" width="1024" height="391" class="alignnone size-large wp-image-1036" /><img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_205013-1024x444.png" alt="snipaste_20170316_205013" width="1024" height="444" class="alignnone size-large wp-image-1045" /><img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_205022-1024x390.png" alt="snipaste_20170316_205022" width="1024" height="390" class="alignnone size-large wp-image-1055" /><img src="https://msdnshared.blob.core.windows.net/media/2017/03/snipaste_20170316_205034-1024x524.png" alt="snipaste_20170316_205034" width="1024" height="524" class="alignnone size-large wp-image-1056" />
]]></content:encoded>
    </item>
    <item>
      <title>Connect to Azure IoT Hub in browser ( using AMQP over WebSockets )</title>
      <link>https://docs.microsoft.com/archive/blogs/zhiqing/connect-to-azure-iot-hub-in-browser-using-amqp-over-websockets</link>
      <pubDate>Tue, 14 Mar 2017 05:10:53 GMT</pubDate>
      <dc:creator><![CDATA[michaeljqzq]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/zhiqing/?p=935</guid>
      <description><![CDATA[div.single > * {
margin-bottom: 15px;
}
#customers {
    font-family: Arial, Helvetica,...]]></description>
      <content:encoded><![CDATA[<style>
div.single > * {
margin-bottom: 15px;
}
#customers {
    font-family: Arial, Helvetica, sans-serif;
    border-collapse: collapse;
    width: 100%;
}
#customers td, #customers th {
    border: 1px solid #ddd;
    padding: 8px;
}#customers tr:nth-child(even){background-color: #f2f2f2;}#customers tr:hover {background-color: #ddd;}#customers th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: grey;
    color: white;
}
</style>

Azure provides simple ways to connect to IoT Hub through <a target="_blank" href="https://github.com/Azure/azure-iot-sdks">azure-iot-sdk</a>, but some developers would like to figure out what the sdk exactly did or integrate with their own services. In this situation, it is necessary to find out how to connect to Azure IoT Hub above protocol level.

AMQP is the only protocol to connect to IoT Hub ( You can find detailed spec of this protocol <a target="_blank" href="https://docs.oasis-open.org/amqp/core/v1.0/amqp-core-complete-v1.0.pdf">here</a>, but trust me, it isn't easy to go through this ). Since using browser to do this is quite convenient for developing and debugging, so we will choose AMQP over WebSockets to connect.

First we have to create a websocket tunnel. Here is the url:
<pre>wss://&lt;YOUR-IOT-HUB-NAME&gt;.azure-devices.net:443/$iothub/websocket

Sec-WebSocket-Protocol: AMQPWSB10
</pre>
<button id="b1" class="btn btn-info" onclick="$('#p1').slideDown();$('#b1').fadeOut();">How to get IoT hub name?</button>
<p id="p1" style="display: none; padding-left: 30px;">You can find it in Azure portal.<img src="https://msdnshared.blob.core.windows.net/media/2017/03/138.png" alt="1" width="1350" height="463" class="alignnone size-full wp-image-945" /></p>


Then you will have to establish AMQP connection. Use the following parameters to connect, you need to use SASL.
<table id="customers">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>hostname</td>
<td>&lt;YOUR-IOT-HUB-NAME&gt;.azure-devices.net</td>
</tr>
<tr>
<td>container_id</td>
<td>"conn" + &lt;CURRENT-TIME-STAMP&gt;</td>
</tr>
<tr>
<td>max_frame_size</td>
<td>4294967295</td>
</tr>
<tr>
<td>channel_max</td>
<td>65535</td>
</tr>
<tr>
<td>idle_timeout</td>
<td>120000</td>
</tr>
<tr>
<td>outgoing_locales</td>
<td>en-US</td>
</tr>
<tr>
<td>incoming_locales</td>
<td>en-US</td>
</tr>
<tr>
<td>offered_capabilities</td>
<td>null</td>
</tr>
<tr>
<td>desired_capabilities</td>
<td>null</td>
</tr>
<tr>
<td>properties</td>
<td>{}</td>
</tr>
<tr>
<td>connection_details</td>
<td>&lt;YOUR-WEBSOCKET-CONNECTION&gt;</td>
</tr>
<tr>
<td>reconnect</td>
<td>false</td>
</tr>
<tr>
<td>username</td>
<td>&lt;ROLE-IN-SHARED-ACCESS-POLICIES&gt;@sas.root.&lt;YOUR-IOT-HUB-NAME&gt;</td>
</tr>
<tr>
<td>password</td>
<td>&lt;Shared Access Signature&gt;</td>
</tr>
</tbody>
</table>
<button id="b2" class="btn btn-info" onclick="$('#p2').slideDown();$('#b2').fadeOut();">What is Shared Access Signature?</button>
<p id="p2" style="display: none;">A shared access signature provides delegated access to resources in your storage account. With a SAS, you can grant clients access to resources in your storage account, without sharing your account keys. This is the key point of using shared access signatures in your applications — a SAS is a secure way to share your storage resources without compromising your account keys.</p>
<button id="b3" class="btn btn-info" onclick="$('#p3').slideDown();$('#b3').fadeOut();">How to generate SAS?</button>
<div id="p3" style="display: none;">

There are two ways to generate SAS.

a.Generate by Device Explorer.

<a target="_blank" href="https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer">Device Explorer</a> is a tool provided by Azure in Windows environment. You can use it to generate SAS token.

First, get IoT Hub connection string from portal

<img src="https://msdnshared.blob.core.windows.net/media/2017/03/224.png" alt="2" width="1831" height="886" class="alignnone size-full wp-image-946" />

Paste connection string in Device Explorer.

<img src="https://msdnshared.blob.core.windows.net/media/2017/03/316.png" alt="3" width="991" height="458" class="alignnone size-full wp-image-956" />

In the same tab, set TTL and click "Generate SAS", you will get SAS token.

<img src="https://msdnshared.blob.core.windows.net/media/2017/03/411.png" alt="4" width="776" height="377" class="alignnone size-full wp-image-955" />

b.Calculate SAS

To save your time and energy,

DON'T use this way if you can generate one using above method.

<span>DON'T use this way if you don't want to investigate a bunch of things about Hash algorithm, signature,etc...</span>

<span>DON'T use this way if you don't have enough reason to do this.</span>

OK. It seems you are still interested in SAS, let's do this!
<pre><signature-string><expiry><keyname><url-encoded-resourceuri>SharedAccessSignature sig=&lt;signature-string&gt;&amp;se=&lt;expiry&gt;&amp;skn=&lt;keyName&gt;&amp;sr=&lt;URL-encoded-resourceURI&gt;
se: expiration time of this token
skn: role in shared access policies<span>
sr: your iot hub url
sig: the SHA-256 hash of the scope of the token with a CRLF appended and an expiry time.</span></url-encoded-resourceuri></keyname></expiry></signature-string></pre>
<pre>sig = hmacHash(_key, sr + '\n' + se) // _key is a base64-encoded key value</pre>
</div>
After connection is established and opened, we need to open a receiver and a sender. We use sender to send cloud-to-device message and use receiver to receive feedback message.(Unfortunately, currently we didn't find a way to fetch device-to-cloud message, we guess we can only do this by connecting EventHub or ServiceBus)
<pre>Sender:/messages/devicebound
Receiver:/messages/serviceBound/feedback
</pre>
OK, now we're finished! You can test with your device to see if it works. If you don't have a device in hand or feel troublesome to use device, you can try our <a target="_blank" href="https://blogs.msdn.microsoft.com/zheli/2017/03/06/web-based-azure-iot-hub-developer-tool/">Web-based Iot device simulator</a>. It can simulator an Iot Device and communicate with IoT Hub. | Connect to Azure IoT Hub in browser ( using AMQP over WebSockets )]]></content:encoded>
    </item>
    <item>
      <title>Use Fiddler to capture websocket packet within non-browser runtime (like Node.js)</title>
      <link>https://docs.microsoft.com/archive/blogs/zhiqing/use-fiddler-to-capture-websocket-packet-within-non-browser-runtime-like-node-js</link>
      <pubDate>Thu, 09 Mar 2017 03:29:42 GMT</pubDate>
      <dc:creator><![CDATA[michaeljqzq]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/zhiqing/?p=875</guid>
      <description><![CDATA[If you would like to skip the zig-zag and find the answer quickly, click me

Recently I'm involved...]]></description>
      <content:encoded><![CDATA[If you would like to skip the zig-zag and find the answer quickly, <a href="#solution">click me</a>

Recently I'm involved in a project which needs to analyze packet of high-level protocol( MQTT , AMQP ) over Websocket. It is quite easy to capture Websocket packet from browser.
Chrome has some support for WS packet capture.
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/117.png" alt="1" width="1920" height="1030" class="alignnone size-full wp-image-876" />

&nbsp;

&nbsp;

However, high-level protocol send Binary data frame, and we can't easily see the binary content.
Fortunately, Fiddler can help us! Fiddler will show a tab "WebSocket" and we can easily see the full content of packets in Websocket like this:
<img src="https://msdnshared.blob.core.windows.net/media/2017/03/25.png" alt="2" width="2561" height="1380" class="alignnone size-full wp-image-886" />

&nbsp;

&nbsp;

But how to capture packet which doesn't come from browser, but from other runtime (for example Node.js)?
I tried npm config first,
<code>
npm config set proxy https://127.0.0.1:8888
npm config set https-proxy https://127.0.0.1:8888
</code>

It seems that this proxy setting only works for requests between client and npm server.

And also tried ways in <a target="_blank" href="https://stackoverflow.com/a/26722381">this answer on SO</a>, but also no luck.

&nbsp;

Finally I found this fantastic tool,<a target="_blank" href="https://www.proxifier.com/">Proxifier</a>. According to its description, it allows network applications that do not support working through proxy servers to operate through a SOCKS or HTTPS proxy and chains.
<div id="solution">

<strong>Here's the detailed steps:</strong>

</div>
<div></div>
<div>1.Configure two settings in Proxifier
a.Proxy server setting:
Profile-&gt;Proxy server , set Fiddler proxy server here.</div>
<div></div>
<div><img src="https://msdnshared.blob.core.windows.net/media/2017/03/36.png" alt="3" width="661" height="523" class="alignnone size-full wp-image-895" /></div>
<div></div>
<div></div>
<div>b.Rule setting:
We have to configure a few rules:
<ul>
 	<li>set Fiddler.exe traffic not go through proxy, or the will be infinite loop</li>
 	<li>set your taget application go through proxy</li>
</ul>
&nbsp;

<img src="https://msdnshared.blob.core.windows.net/media/2017/03/43.png" alt="4" width="985" height="638" class="alignnone size-full wp-image-905" />

</div>
&nbsp;

&nbsp;
<div>

2. If your application use websocket over TLS/SSL, the self-signed certificate provided by Fiddler will be rejected. Trust Fiddler root certificate in system CA list doesn't work.(It seems that Node maintains its own trusted list) So we can configure an environment variable to solve this.
For Windows CMD:

[bash]
set NODE_TLS_REJECT_UNAUTHORIZED=0
[/bash]

For Windows Powershell:

[powershell]
$env:NODE_TLS_REJECT_UNAUTHORIZED = 0
[/powershell]

For unix:

[bash]
export NODE_TLS_REJECT_UNAUTHORIZED=0
[/bash]

Run your application and enjoy!

</div>]]></content:encoded>
    </item>
  </channel>
</rss>