Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

WebSocketStream.cs 2.5 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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
  49. {
  50. get { throw new NotSupportedException(); }
  51. }
  52. public override long Position
  53. {
  54. get { throw new NotSupportedException(); }
  55. set { throw new NotSupportedException(); }
  56. }
  57. public override long Seek(long offset, SeekOrigin origin)
  58. {
  59. throw new NotSupportedException();
  60. }
  61. public override void SetLength(long value)
  62. {
  63. throw new NotSupportedException();
  64. }
  65. }
  66. }