IOS UDP小例子总结

首先需要导入UDP类;

建立通信机制;

点击发送按钮 发送消息,想局域网的所有处在通信端口 (开关开着的情况下)    开关关着就是私聊的情况了

协议方法里实现接收 局域网的消息

运用timer的方法检测局域网的人有谁在

Cell里面显示  同一局域网的人的IP的后缀;

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

@property (nonatomic,copy) NSString *toHost;

@property (weak, nonatomic) IBOutlet UITextField *messageTF;

@property (weak, nonatomic) IBOutlet UISwitch *mySwith;

@property (weak, nonatomic) IBOutlet UILabel *stateLable;

@property (weak, nonatomic) IBOutlet UITextView *historyView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic,strong)AsyncUdpSocket *udpSocket;

 

@property (nonatomic,strong)NSMutableArray *onlineHosts;

@end

 

@implementationViewController

 

- (IBAction)sendMessageAction:(UIButton *)sender {

    NSData *data = [self.messageTF.text dataUsingEncoding:NSUTF8StringEncoding];

    if (self.mySwith.isOn) {//如果开关是开着的,则给所有人发送

        [self.udpSocket sendData:data toHost:@"255.255.255.255" port:9000 withTimeout:-1 tag:0];

        self.historyView.text = [self.historyView.text stringByAppendingFormat:@"\n我对所有人说%@",self.messageTF.text];

       

    }else{//如果开关是关着的,则私聊发送, 目前toHost没有获取到,所以这个代码实现到这里没有作用,需要下面的tableview实现出来后,记录了这个IP才可以。

       

        [self.udpSocket sendData:data toHost:self.toHost port:9000 withTimeout:-1 tag:0];

        self.historyView.text =[self.historyView.text stringByAppendingFormat:@"我对%@:%@",self.toHost,self.messageTF.text];

    }

    

}

- (BOOL)onUdpSocket:(AsyncUdpSocket *)sock

    didReceiveData:(NSData *)data

           withTag:(long)tag

          fromHost:(NSString *)host

              port:(UInt16)port{

    

   if(![host hasSuffix:@":"]) {

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

        if([string isEqualToString:@"谁在线"]) {

            NSData *data = [@"我在线" dataUsingEncoding:NSUTF8StringEncoding];

           [self.udpSocket sendData:data toHost:host port:9000 withTimeout:-1 tag:0];

        }else if ([string isEqualToString:@"我在线"]){

            //把除我之外的IP记录下来Host

           if (![self.onlineHosts containsObject:host]&&![host isEqualToString:@"192.168.1.12"]) {

               [self.onlineHosts addObject:host];

               

               [self.tableView reloadData];

        

           }

           

        }else{//匹配完成后的 聊天内容获取;

            self.messageTF.text = [self.messageTF.text stringByAppendingFormat:@"\n%@说:%@",host,string];

           

       }

    }

    [self.udpSocket receiveWithTimeout:-1 tag:0];

    return  YES;

    

}

 

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

    return  self.onlineHosts.count;

}

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

    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    NSString *host = [[self.onlineHosts[indexPath.row]componentsSeparatedByString:@"."]lastObject];

   cell.textLabel.text = host;

   return cell;

    

}

-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

   self.toHost = self.onlineHosts[indexPath.row];

    self.stateLable.text = [NSString stringWithFormat:@"我对%@说:",self.toHost];

    [self.mySwith setOn:NO animated:YES];

}

 

 

//协议方法:接收别人发的消息

- (void)viewDidLoad {

    [super viewDidLoad];

    self.onlineHosts = [NSMutableArray array];

    self.udpSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];

    [self.udpSocket bindToPort:9000 error:nil];

    [self.udpSocket enableBroadcast:YES error:nil];

    

    [self.udpSocket receiveWithTimeout:-1 tag:0];

    

    [self checkingOnLine];

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(checkingOnLine) userInfo:nil repeats:YES];

}

- (IBAction)switchChange:(UISwitch *)sender {

   if(sender.isOn) {

        self.stateLable.text = @"我对所有人说";

   }else{

        self.stateLable.text = [NSString stringWithFormat:@"我对%@说:",self.toHost];

       if (self.toHost) {

            self.stateLable.text = [NSString stringWithFormat:@"我对%@说:",self.toHost];

       }else{

           [self.mySwith setOn:YES animated:YES];

       }

    }

 

 

}

 

-(void)checkingOnLine{

    NSData *data = [@"谁在线" dataUsingEncoding:NSUTF8StringEncoding ];

                   

    [self.udpSocket sendData:data toHost:@"255.255.255.255" port:9000 withTimeout:-1 tag:0];

}

 

- (void)didReceiveMemoryWarning{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值