DataReaderWriterStream.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
  2. using System;
  3. using System.IO;
  4. using Windows.Storage.Streams;
  5. using System.Runtime.InteropServices.WindowsRuntime;
  6. namespace BestHTTP.PlatformSupport.TcpClient.WinRT
  7. {
  8. public sealed class DataReaderWriterStream : System.IO.Stream
  9. {
  10. private TcpClient Client { get; set; }
  11. public DataReaderWriterStream(TcpClient socket)
  12. {
  13. this.Client = socket;
  14. }
  15. public override bool CanRead { get { return true; } }
  16. public override bool CanSeek { get { return false; } }
  17. public override bool CanWrite { get { return true; } }
  18. public override void Flush() { }
  19. public override long Length { get { throw new NotImplementedException(); } }
  20. public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } }
  21. public bool DataAvailable { get { return true; } }
  22. public override int Read(byte[] buffer, int offset, int count)
  23. {
  24. Windows.Storage.Streams.Buffer tmpBuffer = new Windows.Storage.Streams.Buffer((uint)count);
  25. try
  26. {
  27. var task = Client.Socket.InputStream.ReadAsync(tmpBuffer, tmpBuffer.Capacity, InputStreamOptions.Partial)
  28. .AsTask();
  29. task.ConfigureAwait(false);
  30. task.Wait();
  31. }
  32. catch(AggregateException ex)
  33. {
  34. if (ex.InnerException != null)
  35. throw ex.InnerException;
  36. else
  37. throw ex;
  38. }
  39. DataReader reader = DataReader.FromBuffer(tmpBuffer);
  40. int length = (int)reader.UnconsumedBufferLength;
  41. for (int i = 0; i < length; ++i)
  42. buffer[offset + i] = reader.ReadByte();
  43. return length;
  44. }
  45. public override void Write(byte[] buffer, int offset, int count)
  46. {
  47. var task = Client.Socket.OutputStream.WriteAsync(buffer.AsBuffer(offset, count)).AsTask<uint, uint>();
  48. task.ConfigureAwait(false);
  49. task.Wait();
  50. }
  51. public override long Seek(long offset, System.IO.SeekOrigin origin) { return 0; }
  52. public override void SetLength(long value) { }
  53. }
  54. }
  55. #endif