ConnectingState.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net;
  7. using System.IO;
  8. using System.Threading;
  9. using System.Diagnostics;
  10. namespace Client.SSE
  11. {
  12. public class ConnectingState : IConnectionState
  13. {
  14. private Uri mUrl;
  15. private IWebRequesterFactory mWebRequesterFactory;
  16. private Dictionary<string, string> headers;
  17. public EventSourceState State { get { return EventSourceState.CONNECTING; } }
  18. public ConnectingState(Uri url, IWebRequesterFactory webRequesterFactory, Dictionary<string, string> headers)
  19. {
  20. if (url == null) throw new ArgumentNullException("Url cant be null");
  21. if (webRequesterFactory == null) throw new ArgumentNullException("Factory cant be null");
  22. mUrl = url;
  23. mWebRequesterFactory = webRequesterFactory;
  24. this.headers = headers;
  25. }
  26. public Task<IConnectionState> Run(Action<ServerSentEvent> donothing, CancellationToken cancelToken, Dictionary<string, string> headers)
  27. {
  28. IWebRequester requester = mWebRequesterFactory.Create();
  29. var taskResp = requester.Get(mUrl, headers);
  30. return taskResp.ContinueWith<IConnectionState>(tsk =>
  31. {
  32. if (tsk.Status == TaskStatus.RanToCompletion && !cancelToken.IsCancellationRequested)
  33. {
  34. IServerResponse response = tsk.Result;
  35. if (response.StatusCode == HttpStatusCode.OK)
  36. {
  37. return new ConnectedState(response, mWebRequesterFactory, headers);
  38. }
  39. else
  40. {
  41. Trace.WriteLine("Failed to connect to: " + mUrl.ToString() + response ?? (" Http statuscode: " + response.StatusCode));
  42. }
  43. }
  44. return new DisconnectedState(mUrl, mWebRequesterFactory, headers);
  45. });
  46. }
  47. }
  48. }