Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

85 lignes
2.7 KiB

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