PingServer.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // PingServer.swift
  3. // Swifter
  4. //
  5. // Created by Brian Gerstle on 8/20/16.
  6. // Copyright © 2016 Damian Kołakowski. All rights reserved.
  7. //
  8. import Foundation
  9. import Swifter
  10. // Server
  11. extension HttpServer {
  12. class func pingServer() -> HttpServer {
  13. let server = HttpServer()
  14. server.GET["/ping"] = { request in
  15. return HttpResponse.OK(.Text("pong!"))
  16. }
  17. return server
  18. }
  19. }
  20. let defaultLocalhost = NSURL(string:"http://localhost:8080")!
  21. // Client
  22. extension NSURLSession {
  23. func pingTask(
  24. hostURL: NSURL = defaultLocalhost,
  25. completionHandler handler: (NSData?, NSURLResponse?, NSError?) -> Void
  26. ) -> NSURLSessionDataTask {
  27. return self.dataTaskWithURL(hostURL.URLByAppendingPathComponent("/ping"), completionHandler: handler)
  28. }
  29. func retryPing(
  30. hostURL: NSURL = defaultLocalhost,
  31. timeout: Double = 2.0
  32. ) -> Bool {
  33. let semaphore = dispatch_semaphore_create(0)
  34. self.signalIfPongReceived(semaphore, hostURL: hostURL)
  35. let timeoutDate = NSDate().dateByAddingTimeInterval(timeout)
  36. var timedOut = false
  37. while dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) != 0 {
  38. if NSDate().laterDate(timeoutDate) != timeoutDate {
  39. timedOut = true
  40. break
  41. }
  42. NSRunLoop.currentRunLoop().runMode(
  43. NSRunLoopCommonModes,
  44. beforeDate: NSDate.distantFuture()
  45. )
  46. }
  47. return timedOut
  48. }
  49. func signalIfPongReceived(semaphore: dispatch_semaphore_t, hostURL: NSURL) {
  50. pingTask(hostURL) { data, response, error in
  51. if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200 {
  52. dispatch_semaphore_signal(semaphore)
  53. } else {
  54. self.signalIfPongReceived(semaphore, hostURL: hostURL)
  55. }
  56. }.resume()
  57. }
  58. }