原文地址:http://my.oschina.net/amoyai/blog/91694
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
#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];
| 001 | 下面是用開源的庫Asyncsocket的例子: |
| 004 | //? SocketDemoViewController.h |
| 007 | //? Created by xiang xiva on 10-7-10. |
| 008 | //? Copyright 2010 __MyCompanyName__. All rights reserved. |
| 012 | #import "AsyncSocket.h" |
| 013 | #define SRV_CONNECTED 0 |
| 014 | #define SRV_CONNECT_SUC 1 |
| 015 | #define SRV_CONNECT_FAIL 2 |
| 016 | #define HOST_IP @"192.168.110.1" |
| 017 | #define HOST_PORT 8080 |
| 019 | @interface SocketDemoViewController : UIViewController { |
| 021 | ?UITextField *inputMsg; |
| 026 | @property (nonatomic, retain) AsyncSocket *client; |
| 027 | @property (nonatomic, retain) IBOutlet UITextField *inputMsg; |
| 028 | @property (nonatomic, retain) IBOutlet UILabel *outputMsg; |
| 030 | - (int) connectServer: (NSString *) hostIP port:(int) hostPort; |
| 031 | - (void) showMessage:(NSString *) msg; |
| 033 | - (IBAction) reConnect; |
| 034 | - (IBAction) textFieldDoneEditing:(id)sender; |
| 035 | - (IBAction) backgroundTouch:(id)sender; |
| 042 | //? SocketDemoViewController.m |
| 045 | //? Created by xiang xiva on 10-7-10. |
| 046 | //? Copyright 2010 __MyCompanyName__. All rights reserved. |
| 049 | #import "SocketDemoViewController.h" |
| 051 | @implementation SocketDemoViewController |
| 053 | @synthesize inputMsg, outputMsg; |
| 074 | // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. |
| 076 | ????//[super viewDidLoad]; |
| 077 | ?[self connectServer:HOST_IP port:HOST_PORT]; |
| 084 | // Override to allow orientations other than the default portrait orientation. |
| 085 | - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { |
| 089 | - (void)didReceiveMemoryWarning { |
| 090 | ?// Releases the view if it doesn't have a superview. |
| 091 | ????[super didReceiveMemoryWarning]; |
| 093 | ?// Release any cached data, images, etc that aren't in use. |
| 096 | - (void)viewDidUnload { |
| 098 | ?// Release any retained subviews of the main view. |
| 099 | ?// e.g. self.myOutlet = nil; |
| 102 | - (int) connectServer: (NSString *) hostIP port:(int) hostPort{ |
| 105 | ??client = [[AsyncSocket alloc] initWithDelegate:self]; |
| 108 | ??if (![client connectToHost:hostIP onPort:hostPort error:&err]) { |
| 109 | ???NSLog(@"%@ %@", [err code], [err localizedDescription]); |
| 111 | ???UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host " |
| 112 | ???????????stringByAppendingString:hostIP] |
| 113 | ???????????????message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]] |
| 114 | ?????????????????delegate:self |
| 115 | ??????????????cancelButtonTitle:@"OK" |
| 116 | ??????????????otherButtonTitles:nil]; |
| 120 | ???return SRV_CONNECT_FAIL; |
| 122 | ???NSLog(@"Conectou!"); |
| 123 | ???return SRV_CONNECT_SUC; |
| 127 | ??[client readDataWithTimeout:-1 tag:0]; |
| 128 | ??return SRV_CONNECTED; |
| 133 | - (IBAction) reConnect{ |
| 134 | ?int stat = [self connectServer:HOST_IP port:HOST_PORT]; |
| 136 | ??case SRV_CONNECT_SUC: |
| 137 | ???[self showMessage:@"connect success"]; |
| 140 | ???[self showMessage:@"It's connected,don't agian"]; |
| 149 | ?NSString *inputMsgStr = self.inputMsg.text; |
| 150 | ?NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"]; |
| 151 | ?NSLog(@"%a",content); |
| 152 | ?NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding]; |
| 153 | ?[client writeData:data withTimeout:-1 tag:0]; |
| 157 | ?//[inputMsgStr release]; |
| 159 | ?//[client readDataWithTimeout:-1 tag:0]; |
| 163 | #pragma mark close Keyboard |
| 164 | - (IBAction) textFieldDoneEditing:(id)sender{ |
| 165 | ?[sender resignFirstResponder]; |
| 168 | - (IBAction) backgroundTouch:(id)sender{ |
| 169 | ?[inputMsg resignFirstResponder]; |
| 172 | #pragma mark socket uitl |
| 174 | - (void) showMessage:(NSString *) msg{ |
| 175 | ?UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!" |
| 176 | ????????????????????????????????????????????????????message:msg |
| 177 | ???????????????????????????????????????????????????delegate:nil |
| 178 | ??????????????????????????????????????????cancelButtonTitle:@"OK" |
| 179 | ??????????????????????????????????????????otherButtonTitles:nil]; |
| 185 | #pragma mark socket delegate |
| 187 | - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{ |
| 188 | ?[client readDataWithTimeout:-1 tag:0]; |
| 191 | - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err |
| 196 | - (void)onSocketDidDisconnect:(AsyncSocket *)sock |
| 198 | ?NSString *msg = @"Sorry this connect is failure"; |
| 199 | ?[self showMessage:msg]; |
| 204 | - (void)onSocketDidSecure:(AsyncSocket *)sock{ |
| 208 | - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{ |
| 210 | ?NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; |
| 211 | ?NSLog(@"Hava received datas is :%@",aStr); |
| 212 | ?self.outputMsg.text = aStr; |
| 214 | ?[client readDataWithTimeout:-1 tag:0]; |
總結
以上是生活随笔為你收集整理的socket第三方库nbsp;AsyncSocket(…的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。