From 162c1d53b8714ff97d9d7cf1e12df71fc236cd41 Mon Sep 17 00:00:00 2001 From: Jorge Bernal Date: Tue, 27 Dec 2016 15:56:01 +0100 Subject: [PATCH 1/2] Keep isConnecting true while connecting. The existing code only prevented a second connection to be created while createHTTPRequest was being called (setting up the HTTP request and the streams). However, between the time when the socket opens the streams until the TCP handshake ends, it would be both `!conneted` and `!isConnecting`, which wouldn't prevent a second `connect`. --- Source/WebSocket.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Source/WebSocket.swift b/Source/WebSocket.swift index ca0ebe27..294af0e1 100644 --- a/Source/WebSocket.swift +++ b/Source/WebSocket.swift @@ -190,7 +190,6 @@ open class WebSocket : NSObject, StreamDelegate { didDisconnect = false isConnecting = true createHTTPRequest() - isConnecting = false } /** @@ -494,6 +493,7 @@ open class WebSocket : NSObject, StreamDelegate { let code = processHTTP(buffer, bufferLen: bufferLen) switch code { case 0: + isConnecting = false connected = true guard canDispatch else {return} callbackQueue.async { [weak self] in @@ -906,6 +906,7 @@ open class WebSocket : NSObject, StreamDelegate { private func doDisconnect(_ error: NSError?) { guard !didDisconnect else { return } didDisconnect = true + isConnecting = false connected = false guard canDispatch else {return} callbackQueue.async { [weak self] in From 14313df360c12bfa0d760c0bffb9ccbab16f6c43 Mon Sep 17 00:00:00 2001 From: Jorge Bernal Date: Tue, 27 Dec 2016 16:23:39 +0100 Subject: [PATCH 2/2] Disconnect and clean up streams before connecting. Since `disconnect` without a timeout only sends a close message to the server, if we tried to `connect` the socket again before the connection was closed it would not clean up the streams properly, which could result in a crash. See #272 --- Source/WebSocket.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Source/WebSocket.swift b/Source/WebSocket.swift index 294af0e1..68cb36af 100644 --- a/Source/WebSocket.swift +++ b/Source/WebSocket.swift @@ -318,6 +318,9 @@ open class WebSocket : NSObject, StreamDelegate { //higher level API we will cut over to at some point //NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream) + // Disconnect and clean up any existing streams before setting up a new pair + disconnectStream(nil) + var readStream: Unmanaged? var writeStream: Unmanaged? let h = url.host! as NSString