導入AsynSocket庫,導入CFNetwork系統庫
1.新建single view工程
ViewController.h文件
#import#import "AsyncSocket.h" @interface ViewController : UIViewController { NSMutableArray *_socketArray; AsyncSocket *_sendSocket;//發送 AsyncSocket *_recvSocket;//接收 } - (IBAction)sendClick:(id)sender; @property (retain, nonatomic) IBOutlet UITextField *ipField; @property (retain, nonatomic) IBOutlet UITextField *sendField; @property (retain, nonatomic) IBOutlet UITextView *msgView; - (IBAction)conClick:(id)sender; - (IBAction)sendClick:(id)sender; @end
#import "ViewController.h"
@implementation ViewController
@synthesize ipField;
@synthesize sendField;
@synthesize msgView;
- (void)viewDidLoad
{
[super viewDidLoad];
//初始化socket數組,存放socket
_socketArray = [[NSMutableArray alloc] init];
//實例化客戶端和服務器socket
_sendSocket = [[AsyncSocket alloc] initWithDelegate:self];
_recvSocket = [[AsyncSocket alloc] initWithDelegate:self];
//服務器段開始監聽
[_recvSocket acceptOnPort:5566 error:nil];
}
//服務器端接收到新的socket
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
//服務器端將收到的socket存入數組
[_socketArray addObject:newSocket];
//開始接收數據
[newSocket readDataWithTimeout:-1 tag:0];
}
//服務器端接收到信息
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
self.msgView.text = [NSString stringWithFormat:@"%@%@:%@\n", self.msgView.text, sock.connectedHost, string];
[sock readDataWithTimeout:-1 tag:0];//循環
}
//連接
- (IBAction)conClick:(id)sender {
if (_sendSocket.isConnected) {
[_sendSocket disconnect];
}
[_sendSocket connectToHost:self.ipField.text onPort:5566 withTimeout:30 error:nil];
}
//發送消息
- (IBAction)sendClick:(id)sender {
NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding];
[_sendSocket writeData:data withTimeout:30 tag:0];
self.sendField.text = @"";
}
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"連接服務器成功");
}
- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"斷開連接");
}
- (void)dealloc {
[ipField release];
[sendField release];
[msgView release];
[ipField release];
[super dealloc];
}
- (void)viewDidUnload {
[self setIpField:nil];
[super viewDidUnload];
}
@end