演示效果 :

 

导入附件(AsyncUdpSocket

1_ .h 文件

  1. #import <UIKit/UIKit.h> 
  2. #import "AsyncUdpSocket.h" 
  3. @interface ViewController : UIViewController<AsyncUdpSocketDelegate> 
  4.     AsyncUdpSocket *recvSocket; 
  5.     AsyncUdpSocket *sendSocket; 
  6. @property (retain, nonatomic) IBOutlet UITextField *ipField; 
  7. @property (retain, nonatomic) IBOutlet UITextField *sendField; 
  8. @property (retain, nonatomic) IBOutlet UITextView *contentView; 
  9.  
  10. - (IBAction)sendText:(id)sender; 
  11. @end 


2_ .m 文件

  1. #import "ViewController.h" 
  2.  
  3. @implementation ViewController 
  4. @synthesize ipField; 
  5. @synthesize sendField; 
  6. @synthesize contentView; 
  7.  
  8. #pragma mark - View lifecycle 
  9.  
  10. - (void)viewDidLoad 
  11.     [super viewDidLoad]; 
  12.      
  13.     recvSocket = [[AsyncUdpSocket alloc]initWithDelegate:self]; 
  14.     //  绑定端口  
  15.     [recvSocket bindToPort:5888 error:nil]; 
  16.      
  17.     sendSocket = [[AsyncUdpSocket alloc]initWithDelegate:self]; 
  18.     //  绑定端口  端口应该和接受端 不同 
  19.     [sendSocket bindToPort:5999 error:nil]; 
  20.      
  21.     // 等待接收数据 
  22.     [recvSocket receiveWithTimeout:-1 tag:100]; 
  23.     // 什么时候接受到了数据呢? 
  24.  
  25. // 调用这个方法表示接受到了 数据 
  26. - (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port 
  27.     NSString *str = [[[NSString alloc] initWithData:data 
  28.                                            encoding:NSUTF8StringEncoding]autorelease]; 
  29.     contentView.text = [NSString stringWithFormat:@"%@\n%@:%@",contentView.text,host,str]; 
  30.     [recvSocket receiveWithTimeout:-1 tag:100]; 
  31.      
  32.     return YES; 
  33.  
  34. - (IBAction)sendText:(id)sender { 
  35.     NSData *data = [sendField.text dataUsingEncoding:NSUTF8StringEncoding]; 
  36.     [sendSocket sendData:data toHost:ipField.text port:5888 withTimeout:60 tag:100]; 
  37.     //什么时候发送成功 
  38. // 调用这个方法表示发送成功 
  39. - (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag 
  40.      
  41.  
  42.  
  43. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
  44.     [ipField resignFirstResponder]; 
  45.     [sendField resignFirstResponder]; 
  46.  
  47. - (void)viewDidUnload 
  48.     [self setIpField:nil]; 
  49.     [self setSendField:nil]; 
  50.     [self setContentView:nil]; 
  51.     [super viewDidUnload]; 
  52.     // Release any retained subviews of the main view. 
  53.     // e.g. self.myOutlet = nil
  54. - (void)dealloc { 
  55.     [ipField release]; 
  56.     [sendField release]; 
  57.     [contentView release]; 
  58.     [super dealloc]; 
  59.  
  60. @end