演示效果 :
导入附件(AsyncUdpSocket)
1_ .h 文件
- #import <UIKit/UIKit.h>
- #import "AsyncUdpSocket.h"
- @interface ViewController : UIViewController<AsyncUdpSocketDelegate>
- {
- AsyncUdpSocket *recvSocket;
- AsyncUdpSocket *sendSocket;
- }
- @property (retain, nonatomic) IBOutlet UITextField *ipField;
- @property (retain, nonatomic) IBOutlet UITextField *sendField;
- @property (retain, nonatomic) IBOutlet UITextView *contentView;
- - (IBAction)sendText:(id)sender;
- @end
2_ .m 文件
- #import "ViewController.h"
- @implementation ViewController
- @synthesize ipField;
- @synthesize sendField;
- @synthesize contentView;
- #pragma mark - View lifecycle
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- recvSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
- // 绑定端口
- [recvSocket bindToPort:5888 error:nil];
- sendSocket = [[AsyncUdpSocket alloc]initWithDelegate:self];
- // 绑定端口 端口应该和接受端 不同
- [sendSocket bindToPort:5999 error:nil];
- // 等待接收数据
- [recvSocket receiveWithTimeout:-1 tag:100];
- // 什么时候接受到了数据呢?
- }
- // 调用这个方法表示接受到了 数据
- - (BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
- {
- NSString *str = [[[NSString alloc] initWithData:data
- encoding:NSUTF8StringEncoding]autorelease];
- contentView.text = [NSString stringWithFormat:@"%@\n%@:%@",contentView.text,host,str];
- [recvSocket receiveWithTimeout:-1 tag:100];
- return YES;
- }
- - (IBAction)sendText:(id)sender {
- NSData *data = [sendField.text dataUsingEncoding:NSUTF8StringEncoding];
- [sendSocket sendData:data toHost:ipField.text port:5888 withTimeout:60 tag:100];
- //什么时候发送成功
- }
- // 调用这个方法表示发送成功
- - (void)onUdpSocket:(AsyncUdpSocket *)sock didSendDataWithTag:(long)tag
- {
- }
- - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
- [ipField resignFirstResponder];
- [sendField resignFirstResponder];
- }
- - (void)viewDidUnload
- {
- [self setIpField:nil];
- [self setSendField:nil];
- [self setContentView:nil];
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- // e.g. self.myOutlet = nil;
- }
- - (void)dealloc {
- [ipField release];
- [sendField release];
- [contentView release];
- [super dealloc];
- }
- @end
转载于:https://blog.51cto.com/jerejobs/1128348