您的位置:首页 > 移动开发 > IOS开发

IOS UDP小例子总结

2015-09-25 17:41 423 查看
首先需要导入UDP类;
建立通信机制;
点击发送按钮
发送消息,想局域网的所有处在通信端口
(开关开着的情况下)   
开关关着就是私聊的情况了
协议方法里实现接收
局域网的消息
运用timer的方法检测局域网的人有谁在
Cell里面显示 
同一局域网的人的
4000
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
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IOS udp 网络 刘国斌