GCDAsyncUdpSocket Demo

#import "ViewController.h"

#import "GCDAsyncUdpSocket.h"


#define STATUS_HEIGHT         20

#define IPHONE_WIDTH         [UIScreen mainScreen].bounds.size.width

#define IPHONE_HEIGHT        ([UIScreen mainScreen].bounds.size.height -([UIApplication sharedApplication].statusBarFrame.size.height - STATUS_HEIGHT))


@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,GCDAsyncUdpSocketDelegate>

{

    UITextField* _ipTextField;

    UITextField* _portTextField;

    UITableView* _logTableView;

    NSMutableArray* _logArr;

    NSMutableArray* _showArr;

    dispatch_queue_t _sendQueue;

    GCDAsyncUdpSocket* _udpSocket;

    NSRecursiveLock* _lock;

    int _index;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    _logArr = [[NSMutableArray alloc] init];

    _showArr = [[NSMutableArray alloc] init];

    _lock = [[NSRecursiveLock alloc] init];

    

    UITextField* ipTextField = [[UITextField alloc] initWithFrame:CGRectMake(20, 40, 160, 30)];

    _ipTextField = ipTextField;

    ipTextField.backgroundColor = [UIColor clearColor];

    ipTextField.borderStyle = UITextBorderStyleLine;

    ipTextField.tintColor = [UIColor blueColor];

    ipTextField.text = @"45.249.244.38";

    ipTextField.font = [UIFont systemFontOfSize:18];

    [self.view addSubview:ipTextField];

    

    UITextField* portTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(ipTextField.frame)+10, 40, 80, 30)];

    _portTextField = portTextField;

    portTextField.backgroundColor = [UIColor clearColor];

    portTextField.borderStyle = UITextBorderStyleLine;

    portTextField.tintColor = [UIColor blueColor];

    portTextField.text = @"15000";

    portTextField.font = [UIFont systemFontOfSize:18];

    [self.view addSubview:portTextField];

    

    UIButton* sendBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(portTextField.frame)+10, 40, 60, 30)];

    sendBtn.backgroundColor = [UIColor orangeColor];

    [sendBtn setTitle:@"send" forState:UIControlStateNormal];

    [sendBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [sendBtn addTarget:self action:@selector(udpSend:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:sendBtn];

    

    UITableView* logTableView = [[UITableView alloc] initWithFrame:CGRectMake(20,CGRectGetMaxY(sendBtn.frame)+20, IPHONE_WIDTH-40, IPHONE_HEIGHT - CGRectGetMaxY(sendBtn.frame) - 60) style:UITableViewStylePlain];

    _logTableView = logTableView;

    logTableView.backgroundColor = [UIColor whiteColor];

    logTableView.dataSource = self;

    logTableView.delegate = self;

    logTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    logTableView.tableFooterView = [[UIView alloc] init];

    [self.view addSubview:logTableView];

    

}


#pragma mark  - udp send

-(void)udpSend:(UIButton*)btn{

    _udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

    NSError * error = nil;

    NSString* ip = _ipTextField.text;

    int port = [_portTextField.text intValue];

    [_udpSocket bindToPort:port error:&error];

    if (error) {

        NSLog(@"error:%@",error);

    }else {

        [_udpSocket beginReceiving:&error];

    }

    _index = 0;

    _sendQueue = dispatch_queue_create("udp_send_queue", DISPATCH_QUEUE_SERIAL);

    dispatch_async(_sendQueue, ^(){

        while (true) {

            NSData * sendData = [[NSString stringWithFormat:@"%d",_index] dataUsingEncoding:NSUTF8StringEncoding];

            [_udpSocket sendData:sendData toHost:ip port:port withTimeout:-1 tag:0];

            NSString* str = [NSString stringWithFormat:@"send : %d",_index];

            _index++;

            NSLog(str);

            [self addLog:str];

            [NSThread sleepForTimeInterval:1.0];

            

            if (_index % 5 == 0) {

                dispatch_async(dispatch_get_main_queue(), ^(){

                    [self copyLog];

                    [_logTableView reloadData];

                });

            }

            

        }

    });

}



#pragma mark - GCDAsyncUdpSocket delegate

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag

{

    NSLog(@"发送信息成功");

}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error

{

    NSLog(@"发送信息失败");

}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext

{

    NSString* recvStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSString* saveStr = [NSString stringWithFormat:@"------ recv : %@",recvStr];

    NSLog(saveStr);

    [self addLog:saveStr];

}


- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError *)error

{

    NSLog(@"udpSocket关闭");

}




#pragma mark - table view delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    

    static NSString *identifierHot = @"udplog";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierHot];

    if(!cell){

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierHot];

    }

    cell.textLabel.text = _showArr[indexPath.row];

    cell.textLabel.font = [UIFont systemFontOfSize:12];

    cell.backgroundColor = [UIColor clearColor];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;

}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return _showArr.count;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 14;

}



#pragma mark - arr manage

-(void)addLog:(NSString*)str

{

    [_lock lock];

    [_logArr addObject:str];

    [_lock unlock];

}

-(void)copyLog

{

    [_lock lock];

    [_showArr removeAllObjects];

    [_showArr addObjectsFromArray:_logArr];

    [_lock unlock];

}



- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值