admin管理员组

文章数量:1532656

2024年2月8日发(作者:)

@property(nonatomic, strong) NSString *urlString;@property(nonatomic, assign) NSUInteger currentCount; //当前重连次数@end@implementation HXSocketManager+ (instancetype)sharedInstance { static dispatch_once_t onceToken; static HXSocketManager *instance = nil; dispatch_once(&onceToken,^{ instance = [[super allocWithZone:NULL] init]; me = 3; ectCount = NSUIntegerMax; ing = WSUrl;

// 开启ping定时器 mer = [NSTimer scheduledTimerWithTimeInterval:10 target:instance selector:@selector(sendPingMessage) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:mer forMode:NSRunLoopCommonModes]; }); return instance;}+ (id)allocWithZone:(struct _NSZone *)zone{ return [self sharedInstance];}/** 开始连接 */- (void)connect { //先关闭 [ket close]; te = nil;

//后开启 ket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:ing]]]; te = self;

= HXSocketStatusConnecting;

[ket open];}/** 关闭连接 */- (void)close { [ket close]; ket = nil;

[ invalidate]; = nil;}/** 重新连接 */- (void)reconnect {

if (tCount < ectCount) {

//计数器+1 tCount ++;

/** Called when a given web socket was open and authenticated.

@param webSocket An instance of `SRWebSocket` that was open. */- (void)webSocketDidOpen:(SRWebSocket *)webSocket {

NSLog(@"已链接服务器:%@",);

//重置计数器 tCount = 0;

= HXSocketStatusConnected;}/** Called when a given web socket encountered an error.

@param webSocket An instance of `SRWebSocket` that failed with an error. @param error An instance of `NSError`. */- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {

NSLog(@"链接失败:%@",zedDescription);

= HXSocketStatusFailed;

//尝试重新连接 [self reconnect];}/** Called when a given web socket was closed.

@param webSocket An instance of `SRWebSocket` that was closed. @param code Code reported by the server. @param reason Reason in a form of a String that was reported by the server or `nil`. @param wasClean Boolean value indicating whether a socket was closed in a clean state. */- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(nullable NSString *)reason wasClean:(BOOL)wasClean {

NSLog(@"链接已关闭:code:%zd reason:%@",code,reason);

if (code == SRStatusCodeNormal) { = HXSocketStatusClosedByUser; }else { = HXSocketStatusClosedByServer;

//尝试重新连接 [self reconnect]; }}/** Called on receive of a ping message from the server.

@param webSocket An instance of `SRWebSocket` that received a ping frame. @param data Payload that was received or `nil` if there was no payload. */- (void)webSocket:(SRWebSocket *)webSocket didReceivePingWithData:(nullable NSData *)data {

NSLog(@"收到 Ping");}

本文标签: 连接链接重置计数器关闭