导入AsynSocket库,导入CFNetwork系统库
1.新建一个single view工程
ViewController.h文件
#import <UIKit/UIKit.h> #import "AsyncUdpSocket.h" @interface ViewController : UIViewController <AsyncUdpSocketDelegate> { AsyncUdpSocket *_sendSocket; AsyncUdpSocket *_recvSocket; } @property (retain, nonatomic) IBOutlet UITextField *ipField; @property (retain, nonatomic) IBOutlet UITextField *sendField; @property (retain, nonatomic) IBOutlet UITextView *msgView; - (IBAction)sendClick:(id)sender; @end
2.ViewController.m文件
#import "ViewController.h" @implementation ViewController @synthesize ipField; @synthesize sendField; @synthesize msgView; - (void)viewDidLoad { [super viewDidLoad]; _sendSocket = [[AsyncUdpSocket alloc] initWithDelegate:self]; [_sendSocket bindToPort:5555 error:nil]; _recvSocket = [[AsyncUdpSocket alloc] initWithDelegate:self]; [_recvSocket bindToPort:6666 error:nil]; [_recvSocket receiveWithTimeout:-1 tag:0]; } - (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port { NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; self.msgView.text = [NSString stringWithFormat:@"%@%@:%@\n", self.msgView.text, host, string]; [_recvSocket receiveWithTimeout:-1 tag:0]; return YES; } - (IBAction)sendClick:(id)sender { NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding]; [_sendSocket sendData:data toHost:self.ipField.text port:6666 withTimeout:30 tag:0]; self.msgView.text = [NSString stringWithFormat:@"%@我说:%@\n", self.msgView.text, self.sendField.text]; self.sendField.text = @""; } - (void)dealloc { [ipField release]; [sendField release]; [msgView release]; [super dealloc]; } @end
3.ViewController.xib文件