小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

IOS 用封裝API AsyncSocket進行網(wǎng)絡通信

 ccccshq 2014-07-24

AsyncSocket是一個用Object-c封裝好的網(wǎng)絡通訊API,調用方便,容易實現(xiàn)

使用AsyncSocket可以很方便的與其它系統(tǒng)進行Socket通信, AsyncSocket包括TCP和UDP,通過實現(xiàn)委托AsyncSocketDelegate進行交互。

下面是TCP通訊

API 下載地址 :點擊下載

首先,調用此API時需先引入CFNetWork.framework

然后在#import "AsyncSocket.h"就可以直接調用了

閑話不多說,上代碼:

SocketServer端代碼:

.h文件

  1. @interface ViewController :UIViewController<AsyncSocketDelegate,UITextFieldDelegate>  
  2. {  
  3.     AsyncSocket *listener;//監(jiān)聽客戶端請求  
  4.     //AsyncUdpSocket *udpSocket;//不需要即時連接就能通訊  
  5.     NSMutableArray *connectionSockets;//當前請求連接的客戶端  
  6.       
  7.     IBOutlet UITextView *ReceiveData;  
  8.     IBOutlet UITextField *message;  
  9. }  
  10.   
  11. @property (nonatomic, retain)AsyncSocket *listener;  
  12. @property (nonatomic, retain)UITextField *message;  
  13. @property (nonatomic, retain)UITextView *ReceiveData;  
  14.   
  15.   
  16. - (IBAction)sendMessage:(id)sender;  
  17. - (IBAction)textEndEditting:(id)sender;  



.m文件

  1. #import "ViewController.h"  
  2. #import "SocketConfig.h"  
  3.   
  4. @interface ViewController ()  
  5.   
  6. @end  
  7.   
  8. @implementation ViewController  
  9. @synthesize listener;  
  10. @synthesize message,ReceiveData;  
  11. bool isRunning = NO;//判斷當前socket是否已經開始監(jiān)聽socket請求  
  12.   
  13. -(void) sendMessage  
  14. {  
  15.     if(!isRunning)  
  16.     {  
  17.         NSError *error = nil;  
  18.         if (![listeneracceptOnPort:_SERVER_PORT_error:&error]) {  
  19.             return;  
  20.         }  
  21.         NSLog(@"開始監(jiān)聽");  
  22.         isRunning = YES;  
  23.     }  
  24.     else  
  25.     {  
  26.         NSLog(@"重新監(jiān)聽");  
  27.         [listener disconnect];  
  28.         for (int i = 0; i < [connectionSocketscount]; i++) {  
  29.             [[connectionSocketsobjectAtIndex:i]disconnect];  
  30.         }  
  31.         isRunning = FALSE;  
  32.     }  
  33. }  
  34. - (IBAction)sendMessage:(id)sender  
  35. {  
  36.     if(![message.textisEqual:@""])  
  37.     {  
  38.         [listener writeData:[message.textdataUsingEncoding:NSUTF8StringEncoding]  
  39.                 withTimeout:-1 tag:1];  
  40.     }  
  41.     else  
  42.     {  
  43.         UIAlertView *alertView =[[UIAlertViewalloc]initWithTitle:@"Waring"message:@"Please Input Message"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil,nil];  
  44.           
  45.         [alertView show];  
  46.         [alertView release];  
  47.     }  
  48. }  
  49. - (IBAction)textEndEditting:(id)sender  
  50. {  
  51.     [message resignFirstResponder];  
  52. }  
  53. - (void)viewDidLoad  
  54. {  
  55.     ReceiveData.editable=NO;//設置TextView不可以編輯  
  56.     listener=[[AsyncSocketalloc]initWithDelegate:self];  
  57.     message.delegate=self;  
  58.     //初始化連接socket的個數(shù)  
  59.     connectionSockets=[[NSMutableArrayalloc]initWithCapacity:30];  
  60.     [selfsendMessage];  
  61.     [superviewDidLoad];  
  62. // Do any additional setup after loading the view, typically from a nib.  
  63. }  
  64. - (BOOL)textFieldShouldReturn:(UITextField *)textField;  
  65. {  
  66.     [textField resignFirstResponder];  
  67.     return YES;  
  68. }  
  69.   
  70. #pragma socket委托  
  71. //連接socket出錯時調用  
  72. - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err  
  73. {  
  74.     NSLog(@"%@",[errdescription]);  
  75. }  
  76. //收到新的socket連接時調用  
  77. - (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket  
  78. {  
  79.     //將連接服務的客戶端記錄起來,以便以后實現(xiàn)客戶端通信時使用  
  80.     [connectionSockets addObject:newSocket];  
  81. }  
  82. - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag  
  83. {  
  84.     [sock readDataWithTimeout: -1tag: 0];  
  85. }  
  86. //與服務器建立連接時調用(連接成功)  
  87. - (void) onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port  
  88. {  
  89.     //這里的host就是當前進行服務器連接的客戶端ip  
  90.     NSLog(@"host:%@",host);  
  91.     NSString *returnMessage=@"Welcome To Socket Test Server!";  
  92.     //將NSString轉換成為NSData類型  
  93.     NSData *data=[returnMessagedataUsingEncoding:NSUTF8StringEncoding];  
  94.     //向當前連接服務器的客戶端發(fā)送連接成功信息  
  95.     [sock writeData:data withTimeout:-1tag:0];  
  96. }  
  97. /** 
  98.  * Called when a socket has completed reading the requested data into memory. 
  99.  * Not called if there is an error. 
  100.  讀取客戶端發(fā)送來的信息(收到socket信息時調用) 
  101.  **/  
  102. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag  
  103. {  
  104.     NSString *msg = [[[NSStringalloc]initWithData: dataencoding:NSUTF8StringEncoding]autorelease];  
  105.     //獲取當前發(fā)送消息的客戶端ip  
  106.     //NSLog(@"%@",sock.connectedHost);  
  107.     //NSString *ClientIp=[sock connectedHost];  
  108.     NSString *receviceIp=nil;  
  109. //從所有連接的客戶端當中遍歷要接收信息的客戶端  
  110.     for(int i=0;i<[connectionSocketscount];i++)  
  111.     {  
  112.         AsyncSocket *s=(AsyncSocket*)[connectionSocketsobjectAtIndex:i];  
  113.   
  114. //這里要說明一下,在想另外一個客戶端發(fā)送信息時需要指定客戶端ip地址,所以在發(fā)送消息的時候,應該將ip地址一并寫在消息里面,然后由服務端進行處理,我這里這是做了一個簡單的Demo,有2個客戶端相互發(fā)送消息  
  115.   
  116.         if([sock.connectedHostisEqualToString:@"10.0.73.252"])  
  117.         {receviceIp=@"10.0.73.251";}  
  118.         else  
  119.         {receviceIp=@"10.0.73.252";}  
  120.         if([s.connectedHostisEqualToString:receviceIp])  
  121.         {  
  122.             [s writeData:data withTimeout:-1 tag:0];  
  123.             if(msg)  
  124.             {  
  125.                 ReceiveData.text = msg;  
  126.                 NSLog(@"Receive Message:%@",msg);  
  127.             }  
  128.             else  
  129.             {  
  130.                 NSLog(@"Error converting received data into UTF-8 String");  
  131.             }  
  132.         }  
  133.         else  
  134.         {  
  135.            //如果遍歷不存在,則說明客戶端為進行連接  
  136.             NSString *returnMes=@"對方不在線!";  
  137.             NSData *datareturn=[returnMesdataUsingEncoding:NSUTF8StringEncoding];  
  138.             [sock writeData:datareturn withTimeout:-1 tag:0];  
  139.         }  
  140.     }  
  141.   
  142. }  
  143. - (void)onSocketDidDisconnect:(AsyncSocket *)sock  
  144. {  
  145.     [connectionSockets removeObject:sock];  
  146. }  
  147.   
  148. #pragma end Deleagte  
  149.   
  150. - (void)didReceiveMemoryWarning  
  151. {  
  152.     [superdidReceiveMemoryWarning];  
  153.     // Dispose of any resources that can be recreated.  
  154. }  
  155.   
  156. - (void)dealloc  
  157. {  
  158.     [ReceiveData release],ReceiveData=nil;  
  159.     [message release],message=nil;  
  160.     [listener release];  
  161.     [ReceiveData release];  
  162.     [super dealloc];  
  163. }  
  164. @end  






客戶端代碼:

h文件

  1. #import <UIKit/UIKit.h>  
  2. #import "AsyncSocket.h"  
  3.   
  4. @interface ViewController :UIViewController<UITextFieldDelegate>  
  5. {  
  6.     AsyncSocket *socket;  
  7. }  
  8. @property (retain, nonatomic) IBOutlet UITextField *clientIPAddress;  
  9. @property (retain, nonatomic) IBOutlet UITextView *ReceiveData;  
  10. @property (retain, nonatomic) IBOutlet UITextField *SendMessage;  
  11. @property (retain, nonatomic) IBOutlet UILabel *Status;  
  12.   
  13. - (IBAction)Send:(id)sender;  
  14. - (IBAction)ConnectToSever:(id)sender;  
  15. @end  




m文件

  1. #import "ViewController.h"  
  2. #import "Config.h"  
  3. @interface ViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewController  
  8.   
  9. - (void)viewDidLoad  
  10. {  
  11.     _clientIPAddress.delegate=self;  
  12.     [_clientIPAddress setTag:1];  
  13.     _SendMessage.delegate=self;  
  14.     [_SendMessage setTag:2];  
  15.     _ReceiveData.editable=NO;  
  16.     [superviewDidLoad];  
  17. // Do any additional setup after loading the view, typically from a nib.  
  18. }  
  19. - (void) textFieldDidBeginEditing:(UITextField *)textField  
  20. {  
  21.     if([textField tag]==2)  
  22.     {  
  23.         [self viewUp];  
  24.     }  
  25. }  
  26. - (BOOL)textFieldShouldReturn:(UITextField *)textField;  
  27. {  
  28.       
  29.     [textField resignFirstResponder];  
  30.     if([textField tag]==2)  
  31.     {  
  32.         [self viewDown];  
  33.     }  
  34.     return YES;  
  35. }  
  36. - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation  
  37. {  
  38.     returnUIInterfaceOrientationPortrait;  
  39. }  
  40. - (void)didReceiveMemoryWarning  
  41. {  
  42.     [superdidReceiveMemoryWarning];  
  43.     // Dispose of any resources that can be recreated.  
  44. }  
  45. - (IBAction)Send:(id)sender {  
  46.     if(![_SendMessage.textisEqualToString:@""] && ![_clientIPAddress.textisEqualToString:@""])  
  47.     {  
  48.         NSString *message=[NSStringstringWithFormat:@"%@:%@",_clientIPAddress.text,_SendMessage.text];  
  49.         if(socket==nil)  
  50.         {  
  51.             socket=[[AsyncSocketalloc]initWithDelegate:self];  
  52.         }  
  53.         //NSString *content=[message stringByAppendingString:@"\r\n"];  
  54.         [socket writeData:[messagedataUsingEncoding:NSUTF8StringEncoding]withTimeout:-1tag:0];  
  55.         _ReceiveData.text=[NSStringstringWithFormat:@"me:%@",_SendMessage.text];  
  56.     }  
  57.     else  
  58.     {  
  59.         UIAlertView *alert=[[UIAlertViewalloc]initWithTitle:@"Waring"message:@"Please input Message!"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil,nil];  
  60.         [alert show];  
  61.         [alert release];  
  62.     }  
  63. }  
  64.   
  65. - (IBAction)ConnectToSever:(id)sender {  
  66.     if(socket==nil)  
  67.     {  
  68.         socket=[[AsyncSocketalloc]initWithDelegate:self];  
  69.         NSError *error=nil;  
  70.         if(![socketconnectToHost:_IP_ADDRESS_V4_onPort:_SERVER_PORT_error:&error])  
  71.         {  
  72.            _Status.text=@"連接服務器失敗!";  
  73.         }  
  74.         else  
  75.         {  
  76.             _Status.text=@"已連接!";  
  77.         }  
  78.     }  
  79.     else  
  80.     {  
  81.         _Status.text=@"已連接!";  
  82.     }  
  83. }  
  84.   
  85. #pragma AsyncScoket Delagate  
  86. - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {  
  87.     NSLog(@"onSocket:%p didConnectToHost:%@ port:%hu",sock,host,port);  
  88.     [sock readDataWithTimeout:1tag:0];  
  89. }  
  90. - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag  
  91. {  
  92.     [sock readDataWithTimeout: -1tag: 0];  
  93. }  
  94.   
  95. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {  
  96.     NSString* aStr = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];  
  97.     self.ReceiveData.text = aStr;  
  98.     [aStr release];  
  99.     [socket readDataWithTimeout:-1tag:0];  
  100. }  
  101.   
  102. - (void)onSocket:(AsyncSocket *)sock didSecure:(BOOL)flag  
  103. {  
  104.     NSLog(@"onSocket:%p didSecure:YES", sock);  
  105. }  
  106.   
  107. - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err  
  108. {  
  109.     NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);  
  110. }  
  111.   
  112. - (void)onSocketDidDisconnect:(AsyncSocket *)sock  
  113. {  
  114.     //斷開連接了  
  115.     NSLog(@"onSocketDidDisconnect:%p", sock);  
  116.     NSString *msg =@"Sorry this connect is failure";  
  117.     _Status.text=msg;  
  118.     [msg release];  
  119.     socket = nil;  
  120. }  
  121. - (void) viewUp  
  122. {  
  123.     CGRect frame=self.view.frame;  
  124.     frame.origin.y=frame.origin.y-215;  
  125.     [UIView beginAnimations:nilcontext:nil];  
  126.     [UIView setAnimationDuration:0.3f];  
  127.     [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
  128.     self.view.frame=frame;  
  129.     [UIView commitAnimations];  
  130. }  
  131. - (void) viewDown  
  132. {  
  133.     CGRect frame=self.view.frame;  
  134.     frame.origin.y=frame.origin.y+215;  
  135.     [UIView beginAnimations:nilcontext:nil];  
  136.     [UIView setAnimationDuration:0.3f];  
  137.     [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];  
  138.     self.view.frame=frame;  
  139.     [UIView commitAnimations];  
  140. }  
  141. #pragma end Delegate  
  142. - (void)dealloc {  
  143.     [_ReceiveData release];  
  144.     [_SendMessage release];  
  145.     [_Status release];  
  146.     [_clientIPAddress release];  
  147.     [super dealloc];  
  148. }  



Demo下載地址:客戶端下載       服務端下載

微信公眾平臺已開通,加個關注唄。我們一起學習,一起進步
微信號:ios開發(fā)總匯
百度知道群:開發(fā)者俱樂部

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多