单军华
2017-03-10 705dd5bda8a6cdbc97b65e9b046bdf49739cc87b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
//  ReconnectControl.m
//  HeBeiFM
//
//  Created by Apple on 16/9/22.
//  Copyright © 2016年 Apple. All rights reserved.
/**
 断线流程是 每六秒连接一次 如果30秒仍未连接上则通知UI掉线,之后仍然继续连接,知道连接上为止
 */
 
#import "ReconnectControl.h"
#import "GCDAsyncSocket.h"
#import "Socket.h"
 
@interface ReconnectControl ()<GCDAsyncSocketDelegate>
{
    //用于通知UI断线
    VoidBlock _UIBlock;
    //用于通知socket连接成功
    VoidBlock _successBlock;
    //定时器
    NSTimer *_reconnectTimer;
    //socket
    GCDAsyncSocket *_socket;
    //重连次数
    NSInteger _reconnectCount;
    
}
@end
 
@implementation ReconnectControl
 
+(ReconnectControl *)shareControl
{
    static ReconnectControl *control;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        control = [ReconnectControl new];
    });
    return control;
}
 
 
-(void)startReconnectBlock:(VoidBlock)noticeUI success:(VoidBlock)success
 
{
    _UIBlock = noticeUI;
    _successBlock = success;
    _reconnectCount = 0;
    [_reconnectTimer invalidate];
    _reconnectTimer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(reconnect) userInfo:nil repeats:true];
    _status = Reconnecting;
}
 
-(void)reconnect
{
    //当连续5次没有连接成功时通知UI显示断网提示
    if (_reconnectCount == 5) {
        _UIBlock();
    }
    _reconnectCount += 1;
   [self connectHost];
}
 
//连接服务器
-(void)connectHost
{
    _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError *error = nil;
    [_socket connectToHost:[Socket sharedInstance].socketHost onPort:[Socket sharedInstance].socketPort withTimeout:3 error:&error];
}
 
/**
 连接成功后,断开Socket,通知正在等待连接的socket和UI
 */
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    _successBlock();
    _status = ReconnecNone;
    _reconnectCount = 0;
    [_reconnectTimer invalidate];
    [_socket disconnect];
    _socket.delegate = nil;
    NSLog(@"连接成功");
}
@end