Created
November 15, 2015 19:28
-
-
Save jtreanor/4c67d6cc7955fceb5ea1 to your computer and use it in GitHub Desktop.
This simple class takes a SRWebsocket, closes it and retains it until it has been closed. It should prevent https://github.com/square/SocketRocket/pull/169 and other issues.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@import Foundation; | |
@class SRWebSocket; | |
/** | |
This simple class takes a SRWebsocket, closes it and retains it until it has been closed. | |
*/ | |
@interface SRWebSocketCloser : NSObject | |
+ (instancetype)sharedInstance; | |
- (void)addWebSocket:(SRWebSocket *)socket; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "SRWebSocketCloser.h" | |
#import "SRWebSocket.h" | |
@interface SRWebSocketCloser () <SRWebSocketCloser> | |
@property (nonatomic, strong) NSHashTable *websockets; | |
@end | |
@implementation SRWebSocketCloser | |
+ (instancetype)sharedInstance { | |
static SRWebSocketCloser *sharedInstance = nil; | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
sharedInstance = [SRWebSocketCloser new]; | |
}); | |
return sharedInstance; | |
} | |
- (instancetype)init { | |
self = [super init]; | |
if (self) { | |
_websockets = [NSHashTable hashTableWithOptions:NSHashTableStrongMemory|NSPointerFunctionsObjectPointerPersonality]; | |
} | |
return self; | |
} | |
- (void)addWebSocket:(SRWebSocket *)socket { | |
if (!socket) { | |
return; | |
} | |
@synchronized(self) { | |
[self.websockets addObject:socket]; | |
} | |
socket.delegate = self; | |
[socket close]; | |
} | |
- (void)removeWebSocket:(SRWebSocket *)socket { | |
if (!socket) { | |
return; | |
} | |
@synchronized(self) { | |
[self.websockets removeObject:socket]; | |
} | |
} | |
#pragma mark - SRWebSocketDelegate | |
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message { | |
} | |
- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error { | |
[self removeWebSocket:webSocket]; | |
} | |
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean { | |
[self removeWebSocket:webSocket]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment