socket第三方库 AsyncSocket(GCDAsyncSocket)
為什么80%的碼農都做不了架構師?>>> ??
Socket描述了一個IP、端口對。它簡化了程序員的操作,知道對方的IP以及PORT就可以給對方發送消息,再由服務器端來處理發送的這些消息。所以,Socket一定包含了通信的雙發,即客戶端(Client)與服務端(server)。
1)服務端利用Socket監聽端口;
2)客戶端發起連接;
3)服務端返回信息,建立連接,開始通信;
4)客戶端,服務端斷開連接。
1套接字(socket)概念
套接字(socket)是通信的基石,是支持TCP/IP協議的網絡通信的基本操作單元。
應用層通過傳輸層進行數據通信時,TCP會遇到同時為多個應用程序進程提供并發服務的問題。多個TCP連接或多個應用程序進程可能需要通過同一個 TCP協議端口傳輸數據。為了區別不同的應用程序進程和連接,許多計算機操作系統為應用程序與TCP/IP協議交互提供了套接字(Socket)接口。應 用層可以和傳輸層通過Socket接口,區分來自不同應用程序進程或網絡連接的通信,實現數據傳輸的并發服務。
2 建立socket連接
建立Socket連接至少需要一對套接字,其中一個運行于客戶端,稱為ClientSocket,另一個運行于服務器端,稱為ServerSocket。
套接字之間的連接過程分為三個步驟:服務器監聽,客戶端請求,連接確認。
服務器監聽:服務器端套接字并不定位具體的客戶端套接字,而是處于等待連接的狀態,實時監控網絡狀態,等待客戶端的連接請求。
客戶端請求:指客戶端的套接字提出連接請求,要連接的目標是服務器端的套接字。為此,客戶端的套接字必須首先描述它要連接的服務器的套接字,指出服務器端套接字的地址和端口號,然后就向服務器端套接字提出連接請求。
連接確認:當服務器端套接字監聽到或者說接收到客戶端套接字的連接請求時,就響應客戶端套接字的請求,建立一個新的線程,把服務器端套接字的描述發 給客戶端,一旦客戶端確認了此描述,雙方就正式建立連接。而服務器端套接字繼續處于監聽狀態,繼續接收其他客戶端套接字的連接請求。
?
4、SOCKET連接與TCP連接
創建Socket連接時,可以指定使用的傳輸層協議,Socket可以支持不同的傳輸層協議(TCP或UDP),當使用TCP協議進行連接時,該Socket連接就是一個TCP連接。
?
5、Socket連接與HTTP連接
由于通常情況下Socket連接就是TCP連接,因此Socket連接一旦建立,通信雙方即可開始相互發送數據內容,直到雙方連接斷開。但在實際網 絡應用中,客戶端到服務器之間的通信往往需要穿越多個中間節點,例如路由器、網關、防火墻等,大部分防火墻默認會關閉長時間處于非活躍狀態的連接而導致 Socket 連接斷連,因此需要通過輪詢告訴網絡,該連接處于活躍狀態。
而HTTP連接使用的是“請求—響應”的方式,不僅在請求時需要先建立連接,而且需要客戶端向服務器發出請求后,服務器端才能回復數據。
很多情況下,需要服務器端主動向客戶端推送
iphone的標準推薦CFNetwork C庫編程.但是編程比較煩躁。在其它OS往往用類來封裝的對Socket函數的處理。比如MFC的CAsysncSocket.在iphone也有類似于 開源項目.cocoa AsyncSocket庫,?官方網站:http://code.google.com/p/cocoaasyncsocket/?它用來簡化 CFnetwork的調用.
一.在項目引入ASyncSocket庫
??1.下載ASyncSocket庫源碼
??2.把ASyncSocket庫源碼加入項目:只需要增加RunLoop目錄中的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四個文件。
??3.在項目增加CFNetwork框架
?? ? ??在Framework目錄右健,選擇Add-->Existing Files...??? , 選擇?CFNetwork.framework
?
二.TCP客戶端
??1. 在controller頭文件定義AsyncSocket對象
#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
?
@interface HelloiPhoneViewController : UIViewController {
?? ?UITextField ? ?* textField;
?? ?AsyncSocket * asyncSocket;
}
@property (retain, nonatomic) IBOutlet UITextField *textField;
- (IBAction) buttonPressed: (id)sender;
- (IBAction) textFieldDoneEditing: (id)sender; ? ?
@end
?
??2.在需要聯接地方使用connectToHost聯接服務器
??其中initWithDelegate的參數中self是必須。這個對象指針中的各個Socket響應的函數將被ASyncSocket所調用.
?
?? ?asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];?
?? ?NSError *err = nil;?
?? ?if(![asyncSocket connectToHost:host on:port error:&err])?
?? ?{?
?? ? ? ?NSLog(@"Error: %@", err);?
?? ?}?
?
3.增加Socket響應事件
?? ? 因為initWithDelegate把將當前對象傳遞進去,這樣只要在當前對象方法實現相應方法.
?
4.關于NSData對象
?? ?無論SOCKET收發都采用NSData對象.它的定義是?http://developer.apple.com/library/mac /#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html
???NSData主要是帶一個(id)data指向的數據空間和長度 length.
?? ?NSString 轉換成NSData 對象
?
?? ? ?NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding];
?
?? NSData 轉換成NSString對象
?
?? NSData * data;
?? NSString *result = [[NSString alloc] initWithData:data ?encoding:NSUTF8StringEncoding];
?
4.發送數據
?? ? AsyncSocket ?writeData ? ?方法來發送數據,它有如下定義
?? ?- (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;
?
以下是一個實例語句.
?? ? NSData* aData= [@"test data" dataUsingEncoding: NSUTF8StringEncoding];
?? ? [sock writeData:aData withTimeout:-1 tag:1];
?在onSocket重載函數,有如定義采用是專門用來處理SOCKET的發送數據的:
?? ?-(void)onSocket(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
?? ? ?NSLog(@"thread(%),onSocket:%p didWriteDataWithTag:%d",[[NSThread currentThread] name],
?? ? sock,tag);
}?
?
5.接收Socket數據.
?? ?在onSocket重載函數,有如定義采用是專門用來處理SOCKET的接收數據的.
?? ?-(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
在中間將其轉換成NSString進行顯示.
?
?? ?NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];?
?? ?NSLog(@"===%@",aStr);?
?? ?[aStr release];
Asyncsocket的例子 下面是用開源的庫Asyncsocket的例子:// // SocketDemoViewController.h // SocketDemo // // Created by xiang xiva on 10-7-10. // Copyright 2010 __MyCompanyName__. All rights reserved. //#import <UIKit/UIKit.h> #import "AsyncSocket.h" #define SRV_CONNECTED 0 #define SRV_CONNECT_SUC 1 #define SRV_CONNECT_FAIL 2 #define HOST_IP @"192.168.110.1" #define HOST_PORT 8080@interface SocketDemoViewController : UIViewController {UITextField *inputMsg;UILabel *outputMsg;AsyncSocket *client; }@property (nonatomic, retain) AsyncSocket *client; @property (nonatomic, retain) IBOutlet UITextField *inputMsg; @property (nonatomic, retain) IBOutlet UILabel *outputMsg;- (int) connectServer: (NSString *) hostIP port:(int) hostPort; - (void) showMessage:(NSString *) msg; - (IBAction) sendMsg; - (IBAction) reConnect; - (IBAction) textFieldDoneEditing:(id)sender; - (IBAction) backgroundTouch:(id)sender;@end// // SocketDemoViewController.m // SocketDemo // // Created by xiang xiva on 10-7-10. // Copyright 2010 __MyCompanyName__. All rights reserved. //#import "SocketDemoViewController.h"@implementation SocketDemoViewController@synthesize inputMsg, outputMsg; @synthesize client; /* // The designated initializer. Override to perform setup that is required before the view is loaded. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if (self) {// Custom initialization}return self; } *//* // Implement loadView to create a view hierarchy programmatically, without using a nib. - (void)loadView { } */// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad {//[super viewDidLoad];[self connectServer:HOST_IP port:HOST_PORT];//監聽讀取}// Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {return YES; }- (void)didReceiveMemoryWarning {// Releases the view if it doesn't have a superview.[super didReceiveMemoryWarning];// Release any cached data, images, etc that aren't in use. }- (void)viewDidUnload {self.client = nil;// Release any retained subviews of the main view.// e.g. self.myOutlet = nil; }- (int) connectServer: (NSString *) hostIP port:(int) hostPort{if (client == nil) {client = [[AsyncSocket alloc] initWithDelegate:self];NSError *err = nil;//192.168.110.128if (![client connectToHost:hostIP onPort:hostPort error:&err]) {NSLog(@"%@ %@", [err code], [err localizedDescription]);UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "stringByAppendingString:hostIP]message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];[alert show];[alert release];//client = nil;return SRV_CONNECT_FAIL;} else {NSLog(@"Conectou!");return SRV_CONNECT_SUC;}}else {[client readDataWithTimeout:-1 tag:0];return SRV_CONNECTED;}}- (IBAction) reConnect{int stat = [self connectServer:HOST_IP port:HOST_PORT];switch (stat) {case SRV_CONNECT_SUC:[self showMessage:@"connect success"];break;case SRV_CONNECTED:[self showMessage:@"It's connected,don't agian"];break;default:break;} }- (IBAction) sendMsg{NSString *inputMsgStr = self.inputMsg.text;NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];NSLog(@"%a",content);NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];[client writeData:data withTimeout:-1 tag:0];//[data release];//[content release];//[inputMsgStr release];//繼續監聽讀取//[client readDataWithTimeout:-1 tag:0]; }#pragma mark - #pragma mark close Keyboard - (IBAction) textFieldDoneEditing:(id)sender{[sender resignFirstResponder]; }- (IBAction) backgroundTouch:(id)sender{[inputMsg resignFirstResponder]; }#pragma mark socket uitl- (void) showMessage:(NSString *) msg{UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"message:msgdelegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil];[alert show];[alert release]; }#pragma mark socket delegate- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{[client readDataWithTimeout:-1 tag:0]; }- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err {NSLog(@"Error"); }- (void)onSocketDidDisconnect:(AsyncSocket *)sock {NSString *msg = @"Sorry this connect is failure";[self showMessage:msg];[msg release];client = nil; }- (void)onSocketDidSecure:(AsyncSocket *)sock{}- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];NSLog(@"Hava received datas is :%@",aStr);self.outputMsg.text = aStr;[aStr release];[client readDataWithTimeout:-1 tag:0]; }#pragma mark dealloc- (void)dealloc {[client release];[inputMsg release];[outputMsg release];[super dealloc]; }@end
轉載于:https://my.oschina.net/amoyai/blog/91694
總結
以上是生活随笔為你收集整理的socket第三方库 AsyncSocket(GCDAsyncSocket)的全部內容,希望文章能夠幫你解決所遇到的問題。