ViewController.h
1 #import <UIKit/UIKit.h> 2 #import "AsyncUdpSocket.h" 3 4 @interface ViewController : UIViewController 5 <AsyncUdpSocketDelegate> 6 { 7 IBOutlet UITextField *ipField; 8 IBOutlet UITextField *sendField; 9 IBOutlet UITextView *contentView; 10 11 AsyncUdpSocket *recvSocket; 12 AsyncUdpSocket *sendSocket; 13 } 14 15 -(IBAction)sendText:(id)sender; 16 17 @end
ViewController.m
1 #import "ViewController.h" 2 3 @implementation ViewController 4 5 #pragma mark - viewDidLoad 6 7 - (void)viewDidLoad 8 { 9 [super viewDidLoad]; 10 11 //服务端 12 recvSocket = [[AsyncUdpSocket alloc]initWithDelegate:self]; 13 //客户端 14 sendSocket = [[AsyncUdpSocket alloc]initWithDelegate:self]; 15 16 //服务端开始等待别的客户端的连接 17 //65535 >5000 18 [recvSocket bindToPort:5888 error:nil]; 19 [sendSocket bindToPort:5999 error:nil]; 20 21 //等待接受数据 22 [recvSocket receiveWithTimeout:-1 tag:100]; 23 //什么时候接受到了数据 24 } 25 26 #pragma mark - AsyncUdpSocketDelegate 27 //调用这个方法的时候证明接收到了数据 28 -(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port 29 { 30 NSString *str = [[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]autorelease]; 31 contentView.text = [NSString stringWithFormat:@"%@\n%@:%@",contentView.text,host,str]; 32 [recvSocket receiveWithTimeout:-1 tag:100]; 33 return YES; 34 } 35 //这里就发送成功了 36 -(void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag 37 { 38 } 39 40 #pragma mark - .h event 41 -(void)sendText:(id)sender 42 { 43 NSData *data = [sendField.text dataUsingEncoding:NSUTF8StringEncoding]; 44 [sendSocket sendData:data toHost:ipField.text port:5888 withTimeout:60 tag:100]; 45 46 } 47 @end