@@ -121,7 +121,8 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
121121
122122 self . write ( " " , withType: PacketType . CLOSE, withData: nil )
123123 self . ws? . disconnect ( )
124-
124+ self . stopPolling ( )
125+
125126 if fast || self . polling {
126127 self . client? . engineDidClose ( " Disconnect " )
127128 }
@@ -252,7 +253,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
252253 SocketLogger . log ( " Got polling response " , client: self !)
253254
254255 if let str = NSString ( data: data, encoding: NSUTF8StringEncoding) as? String {
255- dispatch_async ( self !. parseQueue) {
256+ dispatch_async ( self !. parseQueue) { [ weak self ] in
256257 self ? . parsePollingMessage ( str)
257258 }
258259 }
@@ -337,7 +338,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
337338 }
338339
339340 self ? . waitingForPost = false
340- dispatch_async ( self !. emitQueue) {
341+ dispatch_async ( self !. emitQueue) { [ weak self ] in
341342 if !self !. fastUpgrade {
342343 self ? . flushWaitingForPost ( )
343344 self ? . doPoll ( )
@@ -363,7 +364,8 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
363364 self . waitingForPoll = false
364365 self . waitingForPost = false
365366
366- if self . client == nil {
367+ // If cancelled we were already closing
368+ if self . client == nil || reason == " cancelled " {
367369 return
368370 }
369371
@@ -445,7 +447,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
445447
446448 if let lengthInt = length. toInt ( ) {
447449 if lengthInt != msg. length {
448- NSLog ( " parsing error: \( str) " )
450+ SocketLogger . err ( " parsing error: \( str) " , client : self )
449451 return
450452 }
451453 }
@@ -630,13 +632,21 @@ public final class SocketEngine: NSObject, WebSocketDelegate, SocketLogClient {
630632 }
631633
632634 self . pingTimer? . invalidate ( )
633- dispatch_async ( dispatch_get_main_queue ( ) ) {
634- self . pingTimer = NSTimer . scheduledTimerWithTimeInterval ( NSTimeInterval ( self . pingInterval!) ,
635- target: self ,
635+ dispatch_async ( dispatch_get_main_queue ( ) ) { [ weak self] in
636+ if self == nil {
637+ return
638+ }
639+
640+ self ? . pingTimer = NSTimer . scheduledTimerWithTimeInterval ( NSTimeInterval ( self !. pingInterval!) ,
641+ target: self !,
636642 selector: Selector ( " sendPing " ) , userInfo: nil , repeats: true )
637643 }
638644 }
639645
646+ func stopPolling( ) {
647+ self . session. invalidateAndCancel ( )
648+ }
649+
640650 private func upgradeTransport( ) {
641651 if self . websocketConnected {
642652 SocketLogger . log ( " Upgrading transport to WebSockets " , client: self )
0 commit comments