iOS開發-AsynUdpSocket – iPhone手機開發技術文章 iPhone軟體開發教學課程

導入AsynSocket庫,導入CFNetwork系統庫

1.新建一個single view工程

ViewController.h文件

#import 
#import "AsyncUdpSocket.h"

@interface ViewController : UIViewController  {
    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文件

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。