Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

78 rindas
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 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. }