Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

80 rader
2.5 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. if (response.MessageType == WebSocketMessageType.Close)
  36. {
  37. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, cancellationToken).ConfigureAwait(false);
  38. }
  39. }
  40. return currentOffset - offset;
  41. }
  42. public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  43. {
  44. return _webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
  45. }
  46. public override int Read(byte[] buffer, int offset, int count)
  47. {
  48. return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
  49. }
  50. public override void Write(byte[] buffer, int offset, int count)
  51. {
  52. WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
  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. }