Skip to content

Commit

Permalink
Reconnect after 2 seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
Dev1an committed Apr 1, 2017
1 parent baad736 commit bbc2621
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions Sources/EventSource.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import Dispatch
import PerfectCURL
import cURL

Expand All @@ -21,17 +22,30 @@ public class EventStream {

public init(from source: String, delegate: @escaping Delegate) {
self.delegate = delegate
let curlObject = CURL(url: source)
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Accept: text/event-stream")
curlObject.setOption(CURLOPT_FOLLOWLOCATION, int: 1)

queue.async {
while true {
let fragment = curlObject.perform()
if let bodyFragment = fragment.3 {
self.parse(String(bytes: bodyFragment, encoding: .utf8)!)
// Setup reconnection timeout (2 seconds)
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .background).asyncAfter(
deadline: .now() + 5,
execute: group.leave
)

let curlObject = CURL(url: source)
curlObject.setOption(CURLOPT_HTTPHEADER, s: "Accept: text/event-stream")
curlObject.setOption(CURLOPT_FOLLOWLOCATION, int: 1)

while true {
let fragment = curlObject.perform()
if let bodyFragment = fragment.3 {
self.parse(String(bytes: bodyFragment, encoding: .utf8)!)
}
if fragment.0 == false { break }
}
if fragment.0 == false { break }

// wait until the timeout is passed
group.wait()
}
}
}
Expand Down

0 comments on commit bbc2621

Please # to comment.