DWNetworkMonitorViewController.m 14.9 KB
Newer Older
Han Ruisong's avatar
Han Ruisong committed
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
//
//  DWNetworkMonitorViewController.m
//  Demo
//
//  Created by zwl on 2018/11/13.
//  Copyright © 2018 com.bokecc.www. All rights reserved.
//

#import "DWNetworkMonitorViewController.h"
#import "DWNetworkMonitor.h"
#import "MBProgressHUD.h"

@interface DWNetworkMonitorViewController ()

//@property(nonatomic,strong)dispatch_queue_t queue;
//@property(nonatomic,assign)CFRunLoopRef networkMonitorRunloop;
//标题
@property(nonatomic,strong)UILabel * titleLabel;
//文本框
@property(nonatomic,strong)UITextView * textView;
@property(nonatomic,strong)UIButton * copyInfoButton;
@property(nonatomic,strong)UIButton * repeatTestButton;

//ping
@property(nonatomic,strong)DWNetworkMonitor * networkMonitor;

@property(nonatomic,strong) NSMutableString * allTextOutput;
@property(nonatomic,strong) NSString * vid;
//开始网络测试 等等等 状态描述
@property(nonatomic,strong) NSString * networkDescription;
Han Ruisong's avatar
Han Ruisong committed
31
@property(nonatomic,strong) HDReachability * reachability;
Han Ruisong's avatar
Han Ruisong committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
@property(nonatomic,strong) NSString * networkStatus;
@property(nonatomic,strong) NSString * localIP;
//@property(nonatomic,strong) NSString * city;
@property(nonatomic,strong) NSString * hostName;
@property(nonatomic,strong) NSArray * packets;
//判断是否需要ping 节点
@property(nonatomic,assign) BOOL isPingNode;

@end

@implementation DWNetworkMonitorViewController

-(instancetype)initWithVideoId:(NSString *)vid
{
    if (self == [super init]) {
                
        //增加网络状态监听
Han Ruisong's avatar
Han Ruisong committed
49
        self.reachability = [HDReachability reachabilityForInternetConnection];
Han Ruisong's avatar
Han Ruisong committed
50
        [self.reachability startNotifier];
Han Ruisong's avatar
Han Ruisong committed
51
52
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kHDReachabilityChangedNotification object:nil];
        HDNetworkStatus status = [_reachability currentReachabilityStatus];
Han Ruisong's avatar
Han Ruisong committed
53
        switch (status) {
Han Ruisong's avatar
Han Ruisong committed
54
            case HDNotReachable:{
Han Ruisong's avatar
Han Ruisong committed
55
56
57
                self.networkStatus = @"未知";
            }
                break;
Han Ruisong's avatar
Han Ruisong committed
58
            case HDReachableViaWiFi:{
Han Ruisong's avatar
Han Ruisong committed
59
60
61
                self.networkStatus = @"WIFI";
            }
                break;
Han Ruisong's avatar
Han Ruisong committed
62
            case HDReachableViaWWAN:{
Han Ruisong's avatar
Han Ruisong committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
                self.networkStatus = @"流量";
            }
                break;
            default:
                break;
        }

        self.isPingNode = NO;
        self.allTextOutput = [[NSMutableString alloc]init];
        self.vid = [vid copy];
        self.networkDescription = @"开始检测网络...";
        self.title = @"网络检测";
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopPingNotification) name:UIApplicationWillResignActiveNotification object:nil];
        
    }
    return self;
}

-(void)stopPingNotification
{
    //进入后台,ping会断开连接,这里停止检测
    if (self.networkMonitor.isPinging) {
        [self.networkMonitor stopPing];
    }
    self.networkMonitor = nil;
}

//销毁
-(void)destroyNoti
{
    if (self.networkMonitor.isPinging) {
        [self.networkMonitor stopPing];
    }
    self.networkMonitor = nil;
    
    [self.reachability stopNotifier];
    self.reachability = nil;
Han Ruisong's avatar
Han Ruisong committed
101
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kHDReachabilityChangedNotification object:nil];
Han Ruisong's avatar
Han Ruisong committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@15);
        make.right.equalTo(@(-15));
        make.top.equalTo(@30);
        make.height.equalTo(@15);
    }];
    
    [self.view addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.mas_bottom).offset(15);
        make.left.equalTo(@(15 - 4));
        make.right.equalTo(@(-15 + 4));
        make.bottom.equalTo(@(-35 - 40 - 20));
    }];
    
    [self.view addSubview:self.copyInfoButton];
    [self.copyInfoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(@(-35));
        make.width.equalTo(@150);
        make.height.equalTo(@40);
        make.right.equalTo(self.view.mas_centerX).offset(-10);
    }];
    
    [self.view addSubview:self.repeatTestButton];
    [self.repeatTestButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_copyInfoButton);
        make.width.and.height.equalTo(_copyInfoButton);
        make.left.equalTo(self.view.mas_centerX).offset(10);
    }];
    
    //设置基础数据显示
    NSMutableAttributedString * tAttrString = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"视频ID %@",self.vid]];
    [tAttrString addAttribute:NSForegroundColorAttributeName value:[DWTools colorWithHexString:@"#333333"] range:NSMakeRange(5, self.vid.length)];
    self.titleLabel.attributedText = tAttrString;
    
    [self appendString:[[NSMutableString alloc]initWithString:[NSString stringWithFormat:@"测试信息\nVideoID:%@\n%@\n当前网络是:%@\n本地出口ip:%@\nping %@\n",self.vid,self.networkDescription,self.networkStatus,self.localIP,self.hostName]]];
    
    [self start];
  
}

//开始ping
-(void)start
{
    //这里根据自己检测逻辑,ping节点即可
    dispatch_queue_t t = dispatch_queue_create("NetworkMonitor.queue.create", NULL);

    dispatch_async(t, ^{
        [self startMainPing];
Han Ruisong's avatar
Han Ruisong committed
161
        CFRunLoopRun();
Han Ruisong's avatar
Han Ruisong committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    });
    
}

//检测bokecc.com
-(void)startMainPing
{
    DWNetworkMonitor * networkMonitor = [[DWNetworkMonitor alloc]initWithPingHostName:self.hostName];
    networkMonitor.finishBlock = ^(NSArray *packets) {
        
//        __strong typeof(weakSelf) strongSelf = weakSelf;
    
        NSInteger packetNum = 0;
        NSInteger receiveNum = 0;
        double time = 0.0;
        for (DWNetworkMonitoringItem * item in packets) {
            
            packetNum++;
            NSString * pingStr = nil;
            if (item.networkDelay == -1) {
                //丢包 没收到received
                pingStr = [NSString stringWithFormat:@"发送%ld字节至 %@ timeout\n",item.packetBytes,item.addressIP];
            }else{
                receiveNum++;
                NSString * networkDelay = [NSString stringWithFormat:@"%.2f",item.networkDelay];
                time += [networkDelay doubleValue];
                pingStr = [NSString stringWithFormat:@"发送%ld字节至 %@ 耗时 %@ ms\n",item.packetBytes,item.addressIP,networkDelay];
            }
            //            [self.allTextOutput appendString:pingStr];
            [self appendString:pingStr];
        }
        
        [self appendString:[NSString stringWithFormat:@"%ld packets transmitted,%ld received,%ld%% packet loss,time %.2lfms\n",packetNum,receiveNum,(NSInteger)(((packetNum - receiveNum) / (double)packetNum) * 100),time]];
        
        if (receiveNum != 0) {
Han Ruisong's avatar
Han Ruisong committed
197

Han Ruisong's avatar
Han Ruisong committed
198
199
200
201
            //如果ping不通,后面的也不需要执行了
            self.isPingNode = YES;
        }
        
Han Ruisong's avatar
Han Ruisong committed
202
203
        [self startNodePing];
        
Han Ruisong's avatar
Han Ruisong committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        //            [strongSelf startNodePing];
        
    };
    [networkMonitor startPing];
    self.networkMonitor = networkMonitor;
}

//检测当前节点
-(void)startNodePing
{
//    __weak typeof(self) weakSelf = self;
    //没ping同,或者主节点为检测
    if (!self.isPingNode || !self.networkMonitor) {
        dispatch_async(dispatch_get_main_queue(), ^{
            _repeatTestButton.selected = NO;
        });
Han Ruisong's avatar
Han Ruisong committed
220
221
        
        CFRunLoopStop(CFRunLoopGetCurrent());
Han Ruisong's avatar
Han Ruisong committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
        return;
    }

    [self appendString:[NSString stringWithFormat:@"当前播放节点%@\n",self.currentPlayurl]];
    NSURL * url = [NSURL URLWithString:self.currentPlayurl];

    [self appendString:[NSString stringWithFormat:@"正在检查与服务器 %@ 的连接信息\n",url.host]];

    //ping 当前播放路径
    DWNetworkMonitor * networkMonitor = [[DWNetworkMonitor alloc]initWithPingHostName:url.host];
    networkMonitor.finishBlock = ^(NSArray *packets) {
        
        //            __strong typeof(weakSelf) strongSelf = weakSelf;
        
        [self replaceOldStr:self.networkDescription AndNewStr:@"检测完毕"];
        self.networkDescription = @"检测完毕";
        
        NSInteger packetNum = 0;
        NSInteger receiveNum = 0;
        double time = 0.0;
        for (DWNetworkMonitoringItem * item in packets) {
            
            packetNum++;
            NSString * pingStr = nil;
            if (item.networkDelay == -1) {
                //丢包 没收到received
                pingStr = [NSString stringWithFormat:@"发送%ld字节至 %@ timeout\n",item.packetBytes,item.addressIP];
            }else{
                receiveNum++;
                NSString * networkDelay = [NSString stringWithFormat:@"%.2f",item.networkDelay];
                time += [networkDelay doubleValue];
                pingStr = [NSString stringWithFormat:@"发送%ld字节至 %@ 耗时 %@ ms\n",item.packetBytes,item.addressIP,networkDelay];
            }
            [self appendString:pingStr];
        }
        
        [self appendString:[NSString stringWithFormat:@"%ld packets transmitted,%ld received,%ld%% packet loss,time %.2lfms\n",packetNum,receiveNum,(NSInteger)(((packetNum - receiveNum) / (double)packetNum) * 100),time]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.repeatTestButton.selected = NO;
        });
Han Ruisong's avatar
Han Ruisong committed
263
264
        
        CFRunLoopStop(CFRunLoopGetCurrent());
Han Ruisong's avatar
Han Ruisong committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    };
    [networkMonitor startPing];
    self.networkMonitor = networkMonitor;
}

//增加数据显示
-(void)appendString:(NSString *)str
{
    [self.allTextOutput appendString:str];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.textView.text = self.allTextOutput;
    });
}

//替换显示数据
-(void)replaceOldStr:(NSString *)oldStr AndNewStr:(NSString *)newStr
{
    NSRange range = [self.allTextOutput rangeOfString:oldStr];
    [self.allTextOutput replaceCharactersInRange:range withString:newStr];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.textView.text = self.allTextOutput;
    });
}

#pragma mark - action
-(void)returnButtonAction
{
    [self destroyNoti];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)networkStateChange
{
    NSString * oldStatus = self.networkStatus;
Han Ruisong's avatar
Han Ruisong committed
299
    HDNetworkStatus status = [_reachability currentReachabilityStatus];
Han Ruisong's avatar
Han Ruisong committed
300
    switch (status) {
Han Ruisong's avatar
Han Ruisong committed
301
        case HDNotReachable:{
Han Ruisong's avatar
Han Ruisong committed
302
303
304
            self.networkStatus = @"未知";
        }
            break;
Han Ruisong's avatar
Han Ruisong committed
305
        case HDReachableViaWiFi:{
Han Ruisong's avatar
Han Ruisong committed
306
307
308
            self.networkStatus = @"WIFI";
        }
            break;
Han Ruisong's avatar
Han Ruisong committed
309
        case HDReachableViaWWAN:{
Han Ruisong's avatar
Han Ruisong committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
            self.networkStatus = @"流量";
        }
            break;
        default:
            break;
    }
    
    [self replaceOldStr:oldStatus AndNewStr:self.networkStatus];
}

-(void)copyInfoButtonAction
{
    //复制信息
    UIPasteboard * pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = _textView.text;
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = @"复制成功";
    [hud hideAnimated:YES afterDelay:3];
}

-(void)repeatTestButtonAction
{
    if (_repeatTestButton.selected) {
        MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.text = @"正在检测中,请稍后";
        [hud hideAnimated:YES afterDelay:3];
        return;
    }
    
    _repeatTestButton.selected = YES;
    
    //清空文字
    [self.allTextOutput setString:[[NSMutableString alloc]initWithString:[NSString stringWithFormat:@"测试信息\nVideoID:%@\n%@\n当前网络是:%@\n本地出口ip:%@\nping %@\n",self.vid,self.networkDescription,self.networkStatus,self.localIP,self.hostName]]];
    self.textView.text = self.allTextOutput;
    
    //重新检测
    [self start];

}
    
#pragma mark - lazyload
-(UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.font = [UIFont systemFontOfSize:15];
        _titleLabel.textColor = [DWTools colorWithHexString:@"#ff920a"];
        _titleLabel.text = @"视频ID";
    }
    return _titleLabel;
}

-(UITextView *)textView
{
    if (!_textView) {
        _textView = [[UITextView alloc]init];
        _textView.font = [UIFont systemFontOfSize:14];
        _textView.textColor = [DWTools colorWithHexString:@"#333333"];
        _textView.showsVerticalScrollIndicator = NO;
        _textView.showsHorizontalScrollIndicator = NO;
        _textView.editable = NO;
    }
    return _textView;
}

-(UIButton *)copyInfoButton
{
    if (!_copyInfoButton) {
        _copyInfoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_copyInfoButton setTitle:@"复制检测信息" forState:UIControlStateNormal];
        [_copyInfoButton setTitleColor:[UIColor colorWithRed:255/255.0 green:146/255.0 blue:10/255.0 alpha:1] forState:UIControlStateNormal];
        _copyInfoButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _copyInfoButton.layer.masksToBounds = YES;
        _copyInfoButton.layer.cornerRadius = 20;
        _copyInfoButton.layer.borderWidth = 1;
        _copyInfoButton.layer.borderColor = [DWTools colorWithHexString:@"#FF920A"].CGColor;
        [_copyInfoButton addTarget:self action:@selector(copyInfoButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _copyInfoButton;
}

-(UIButton *)repeatTestButton
{
    if (!_repeatTestButton) {
        _repeatTestButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_repeatTestButton setTitle:@"重新测试" forState:UIControlStateNormal];
        [_repeatTestButton setTitle:@"测试中" forState:UIControlStateSelected];
        [_repeatTestButton setTitleColor:[DWTools colorWithHexString:@"#333333"] forState:UIControlStateNormal];
        [_repeatTestButton setBackgroundColor:[DWTools colorWithHexString:@"#F3F4F5"]];
        _repeatTestButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _repeatTestButton.layer.masksToBounds = YES;
        _repeatTestButton.layer.cornerRadius = 20;
        _repeatTestButton.selected = YES;
        [_repeatTestButton addTarget:self action:@selector(repeatTestButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _repeatTestButton;
}

-(NSString *)localIP
{
    return [[DWTools getIPAddress] isEqualToString:@"error"] ? @"未获取到ip" : [DWTools getIPAddress];
}

-(NSString *)hostName
{
    return @"p.bokecc.com";
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end