Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

81 řádky
2.6 KiB

  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 WebSocket _webSocket;
  11. public WebSocketStream(WebSocket webSocket)
  12. {
  13. _webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
  14. }
  15. public override bool CanRead => true;
  16. public override bool CanSeek => false;
  17. public override bool CanWrite => true;
  18. public override long Length => throw new NotSupportedException();
  19. public override long Position
  20. {
  21. get => throw new NotSupportedException();
  22. set => throw new NotSupportedException();
  23. }
  24. public override void Flush()
  25. {
  26. }
  27. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  28. {
  29. var currentOffset = offset;
  30. var targetOffset = offset + count;
  31. while (_webSocket.State == WebSocketState.Open && currentOffset < targetOffset)
  32. {
  33. var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, currentOffset, count), cancellationToken).ConfigureAwait(false);
  34. currentOffset += response.Count;
  35. count -= response.Count;
  36. if (response.MessageType == WebSocketMessageType.Close)
  37. {
  38. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
  39. }
  40. }
  41. return currentOffset - offset;
  42. }
  43. public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  44. {
  45. return _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
  46. }
  47. public override int Read(byte[] buffer, int offset, int count)
  48. {
  49. return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
  50. }
  51. public override void Write(byte[] buffer, int offset, int count)
  52. {
  53. WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
  54. }
  55. public override long Seek(long offset, SeekOrigin origin)
  56. {
  57. throw new NotSupportedException();
  58. }
  59. public override void SetLength(long value)
  60. {
  61. throw new NotSupportedException();
  62. }
  63. }
  64. }