標籤:
CocoaAsyncSocket無疑是目前封裝得最完善的Socket庫了:支援非同步TCP/UDP,支援GCD,Objective-C介面封裝,同時還有日誌跟蹤功能,使用此日誌跟蹤,程式員可以很方便的進行調試。
檔案如下:
如果想開啟日誌調試,很簡單,匯入需要的DDASLLogger.h標頭檔,建立DDASLLogger單利對象就可以了。
簡單的示範如下:
1.在故事版布局
2.在ViewController.h檔案中
// ViewController.h// AysnSocket#import <UIKit/UIKit.h>#import "AsyncSocket.h"@interface ViewController : UIViewController{ NSMutableArray *_scokets; //存放用戶端的可變數組 AsyncSocket *_sendSocket; //發送端 AsyncSocket *_receScoket; //接收端}@end
3.在ViewController.m檔案中
// ViewController.m// AysnSocket#import "ViewController.h"#import "AsyncSocket.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UITextView *msgView;@property (weak, nonatomic) IBOutlet UITextField *ipField;@property (weak, nonatomic) IBOutlet UITextField *sendField;- (IBAction)coneClicked:(UIButton *)sender; //串連伺服器- (IBAction)sendClicked:(UIButton *)sender; //發送端發送訊息- (IBAction)disConeClicked:(UIButton *)sender; //中斷連線@end@implementation ViewController@synthesize msgView;@synthesize ipField;@synthesize sendField;- (void)viewDidLoad { [super viewDidLoad]; //1.初始化scokets數組,儲存新的用戶端scoket _scokets = [NSMutableArray array]; //2.執行個體化發送端和接收端 _sendSocket = [[AsyncSocket alloc]initWithDelegate:self]; _receScoket = [[AsyncSocket alloc]initWithDelegate:self]; //3.接收端開始監聽網路 NSError *error; [_receScoket acceptOnPort:8888 error:&error];}#pragma mark - 代理方法//接受到新的scoket- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket{ //將新接收到的socket加入數組中 [_scokets 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:@"%@,%@,%@",self.msgView.text,self.ipField.text,string]; //迴圈讀取 [sock readDataWithTimeout:-1 tag:0];}//串連伺服器成功- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{ NSLog(@"%@",host); NSLog(@"串連伺服器成功");}//斷開伺服器成功-(void)onSocketDidDisconnect:(AsyncSocket *)sock{ NSLog(@"中斷連線成功");}#pragma mark - 按鈕事件//建立串連- (IBAction)coneClicked:(UIButton *)sender { if (_sendSocket.isConnected) { [_sendSocket disconnect]; } //用戶端重新串連到主機 [_sendSocket connectToHost:self.ipField.text onPort:8888 withTimeout:30 error:nil];}//發送訊息- (IBAction)sendClicked:(UIButton *)sender { //用戶端發送資料 NSData *data = [self.sendField.text dataUsingEncoding:NSUTF8StringEncoding]; [_sendSocket writeData:data withTimeout:30 tag:0]; //清空資料 self.sendField.text = @"";}//斷開伺服器- (IBAction)disConeClicked:(UIButton *)sender{ if (_sendSocket.isConnected) { [_sendSocket disconnect]; }}@end
測試如下:
(1)開啟電腦的網路設定,看一下ip和設定連接埠為8888
(2)運行程式,在示範中輸入ip和訊息
一開始: 輸入ip和訊息,然後串連伺服器
串連成功伺服器成功 發送訊息,資料發送成功
斷開伺服器:
斷開伺服器後,再嘗試發送資料,是無法發送並顯示在UITextView上的。
iOS:基於Socket的第三方架構CocoaAsyncSocket的使用