in WindowsDevicePortalWrapper/WindowsDevicePortalWrapper/HttpRest/WebSocket.cs [140:212]
private void StartListeningForMessagesInternal()
{
this.IsListeningForMessages = true;
this.receivingMessagesTask = Task.Run(async () =>
{
try
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[MaxChunkSizeInBytes]);
// Once close message is sent do not try to get any more messages as WDP will abort the web socket connection.
while (this.websocket.State == WebSocketState.Open)
{
// Receive single message in chunks.
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
result = await this.websocket.ReceiveAsync(buffer, CancellationToken.None).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
await this.websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
return;
}
if (result.Count > MaxChunkSizeInBytes)
{
throw new InvalidOperationException("Buffer not large enough");
}
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
Stream stream = new MemoryStream();
await ms.CopyToAsync(stream);
// Ensure we return with the stream pointed at the origin.
stream.Position = 0;
this.ConvertStreamToMessage(stream);
}
}
}
}
catch (WebSocketException e)
{
// If WDP aborted the web socket connection ignore the exception.
SocketException socketException = e.InnerException?.InnerException as SocketException;
if (socketException != null)
{
if (socketException.NativeErrorCode == WSAECONNRESET)
{
return;
}
}
throw;
}
finally
{
this.IsListeningForMessages = false;
}
});
}