From 8e25c6c417995aa57d4a6d8ec16ec565a16f0e75 Mon Sep 17 00:00:00 2001 From: Erik Date: Sun, 7 May 2017 14:01:31 -0400 Subject: [PATCH] Fixes #676 --- SocketIO-MacTests/SocketSideEffectTest.swift | 33 ++++++++++++++++++++ Source/SocketIOClient.swift | 10 +++--- 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/SocketIO-MacTests/SocketSideEffectTest.swift b/SocketIO-MacTests/SocketSideEffectTest.swift index 8f24c63..8969a4a 100644 --- a/SocketIO-MacTests/SocketSideEffectTest.swift +++ b/SocketIO-MacTests/SocketSideEffectTest.swift @@ -221,6 +221,39 @@ class SocketSideEffectTest: XCTestCase { waitForExpectations(timeout: 0.2) } + func testConnectTimesOutIfNotConnected() { + let expect = expectation(description: "The client should call the timeout function") + + socket.setTestStatus(.notConnected) + + socket.connect(timeoutAfter: 1, withHandler: { + expect.fulfill() + }) + + waitForExpectations(timeout: 2) + } + + func testConnectDoesNotTimeOutIfConnected() { + let expect = expectation(description: "The client should not call the timeout function") + + socket.setTestStatus(.notConnected) + + socket.connect(timeoutAfter: 1, withHandler: { + XCTFail("Should not call timeout handler if status is connected") + }) + + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) { + // Fake connecting + self.socket.setTestStatus(.connected) + } + + DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.1) { + expect.fulfill() + } + + waitForExpectations(timeout: 2) + } + let data = "test".data(using: String.Encoding.utf8)! let data2 = "test2".data(using: String.Encoding.utf8)! private var socket: SocketIOClient! diff --git a/Source/SocketIOClient.swift b/Source/SocketIOClient.swift index a9c5123..3896ba7 100644 --- a/Source/SocketIOClient.swift +++ b/Source/SocketIOClient.swift @@ -184,10 +184,8 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So guard timeoutAfter != 0 else { return } - let time = DispatchTime.now() + Double(UInt64(timeoutAfter) * NSEC_PER_SEC) / Double(NSEC_PER_SEC) - - handleQueue.asyncAfter(deadline: time) {[weak self] in - guard let this = self, this.status != .connected && this.status != .disconnected else { return } + handleQueue.asyncAfter(deadline: DispatchTime.now() + Double(timeoutAfter)) {[weak self] in + guard let this = self, this.status == .connecting || this.status == .notConnected else { return } this.status = .disconnected this.engine?.disconnect(reason: "Connect timeout") @@ -555,9 +553,9 @@ open class SocketIOClient : NSObject, SocketIOClientSpec, SocketEngineClient, So } private func _tryReconnect() { - guard reconnecting else { return } + guard reconnects && reconnecting && status != .disconnected else { return } - if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts || !reconnects { + if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts { return didDisconnect(reason: "Reconnect Failed") }