FileConnection.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #if !UNITY_WEBGL || UNITY_EDITOR
  2. using System;
  3. using BestHTTP.Core;
  4. using BestHTTP.Extensions;
  5. using BestHTTP.PlatformSupport.FileSystem;
  6. namespace BestHTTP.Connections
  7. {
  8. internal sealed class FileConnection : ConnectionBase
  9. {
  10. public FileConnection(string serverAddress)
  11. :base(serverAddress)
  12. { }
  13. protected override void ThreadFunc()
  14. {
  15. try
  16. {
  17. // Step 1 : create a stream with header information
  18. // Step 2 : create a stream from the file
  19. // Step 3 : create a StreamList
  20. // Step 4 : create a HTTPResponse object
  21. // Step 5 : call the Receive function of the response object
  22. using (System.IO.Stream fs = HTTPManager.IOService.CreateFileStream(this.CurrentRequest.CurrentUri.LocalPath, FileStreamModes.OpenRead))
  23. using (StreamList stream = new StreamList(new BufferPoolMemoryStream(), fs))
  24. {
  25. // This will write to the MemoryStream
  26. stream.Write("HTTP/1.1 200 Ok\r\n");
  27. stream.Write("Content-Type: application/octet-stream\r\n");
  28. stream.Write("Content-Length: " + fs.Length.ToString() + "\r\n");
  29. stream.Write("\r\n");
  30. stream.Seek(0, System.IO.SeekOrigin.Begin);
  31. base.CurrentRequest.Response = new HTTPResponse(base.CurrentRequest, stream, base.CurrentRequest.UseStreaming, false);
  32. if (!CurrentRequest.Response.Receive())
  33. CurrentRequest.Response = null;
  34. }
  35. }
  36. catch(Exception e)
  37. {
  38. CurrentRequest.Response = null;
  39. if (!CurrentRequest.IsCancellationRequested)
  40. {
  41. CurrentRequest.Exception = e;
  42. CurrentRequest.State = HTTPRequestStates.Error;
  43. }
  44. }
  45. finally
  46. {
  47. if (this.CurrentRequest.IsCancellationRequested)
  48. {
  49. this.CurrentRequest.Response = null;
  50. this.CurrentRequest.State = this.CurrentRequest.IsTimedOut ? HTTPRequestStates.TimedOut : HTTPRequestStates.Aborted;
  51. }
  52. else if (this.CurrentRequest.Response == null)
  53. this.CurrentRequest.State = HTTPRequestStates.Error;
  54. else
  55. this.CurrentRequest.State = HTTPRequestStates.Finished;
  56. ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this, HTTPConnectionStates.Closed));
  57. }
  58. }
  59. }
  60. }
  61. #endif