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


阅读更多
文章标签: GCDAsyncUdpSocket udp
个人分类: iOS
想对作者说点什么? 我来说一句

UDPDEMO基于GCDAsyncUdpSocket

2014年06月06日 384KB 下载

没有更多推荐了,返回首页

不良信息举报

GCDAsyncUdpSocket Demo

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭