Skip to content

Instantly share code, notes, and snippets.

@fzankl
Created January 24, 2021 13:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fzankl/4863b3c6661e4bf595c4a0872fc21913 to your computer and use it in GitHub Desktop.
Exchange data using Azure IoT Hub device streams
public class DeviceStreams
{
...
private static async Task HandleIncomingDataAsync(
NetworkStream localStream,
ClientWebSocket remoteStream,
CancellationToken cancellationToken)
{
var buffer = new byte[10240];
while (remoteStream.State == WebSocketState.Open)
{
var receiveResult = await remoteStream.ReceiveAsync(
buffer, cancellationToken).ConfigureAwait(false);
await localStream.WriteAsync(
buffer, 0, receiveResult.Count).ConfigureAwait(false);
}
}
private static async Task HandleOutgoingDataAsync(
NetworkStream localStream,
ClientWebSocket remoteStream,
CancellationToken cancellationToken)
{
var buffer = new byte[10240];
while (localStream.CanRead)
{
int receiveCount = await localStream.ReadAsync(
buffer, 0, buffer.Length).ConfigureAwait(false);
await remoteStream.SendAsync(
new ArraySegment<byte>(buffer, 0, receiveCount),
WebSocketMessageType.Binary,
endOfMessage: true,
cancellationToken).ConfigureAwait(false);
}
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment