Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

WebSocketStream.cs 2.5 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.IO;
  3. using System.Net.WebSockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace MQTTnet.Implementations
  7. {
  8. public class WebSocketStream : Stream
  9. {
  10. private readonly ClientWebSocket _webSocket;
  11. public WebSocketStream(ClientWebSocket webSocket)
  12. {
  13. _webSocket = webSocket;
  14. }
  15. public override void Flush()
  16. {
  17. }
  18. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  19. {
  20. var currentOffset = offset;
  21. var targetOffset = offset + count;
  22. while (_webSocket.State == WebSocketState.Open && currentOffset < targetOffset)
  23. {
  24. var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, currentOffset, count), cancellationToken).ConfigureAwait(false);
  25. currentOffset += response.Count;
  26. if (response.MessageType == WebSocketMessageType.Close)
  27. {
  28. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
  29. }
  30. }
  31. return currentOffset - offset;
  32. }
  33. public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  34. {
  35. return _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
  36. }
  37. public override int Read(byte[] buffer, int offset, int count)
  38. {
  39. return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
  40. }
  41. public override void Write(byte[] buffer, int offset, int count)
  42. {
  43. WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
  44. }
  45. public override bool CanRead => true;
  46. public override bool CanSeek => false;
  47. public override bool CanWrite => true;
  48. public override long Length => throw new NotSupportedException();
  49. public override long Position
  50. {
  51. get => throw new NotSupportedException();
  52. set => throw new NotSupportedException();
  53. }
  54. public override long Seek(long offset, SeekOrigin origin)
  55. {
  56. throw new NotSupportedException();
  57. }
  58. public override void SetLength(long value)
  59. {
  60. throw new NotSupportedException();
  61. }
  62. }
  63. }