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.

WebSocketStream.cs 2.6 KiB

7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
7 år sedan
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 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. }