导入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;
@end2.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文件
本文介绍了一个使用AsyncUdpSocket进行UDP通信的iOS应用程序示例。该示例包括一个单视图工程,通过ViewController实现了发送和接收UDP数据包的功能。文章详细展示了ViewController.h和ViewController.m文件的内容,包括初始化AsyncUdpSocket实例、设置代理方法以及实现发送和接收数据的逻辑。

被折叠的 条评论
为什么被折叠?



