1. 程式人生 > >iOS Socket第三方開源類庫 AsyncSocket

iOS Socket第三方開源類庫 AsyncSocket

               

假如你也是一個java程式設計師,而你又不是很懂Socket。

下面我的這篇文章也許能幫助你一些。

首先我們寫好上面文章中的server端。

下面我們可以訪問一下下面的地址:

這是一個開源框架。呵,不知道拿到自己程式中使用是否涉及侵權。

但是這句話“The CocoaAsyncSocket project is in the public domain.”是我有信心使用它們的原始碼,否則只能自己用c來寫了,或者使用CFSocket、CFNetwork等類自己來寫了。不過也無妨,應在在使用執行緒的情況下,我們也是可以實現的。

總之,為了開發的便捷,我使用了AsyncSocket這個類,這樣可以非同步通訊。

我們AsyncSocket.h和AsyncSocket.m到我們的專案中,並且匯入CFNetwork.framework。這樣基本準備工作就做好了。

下面提供我的應用中的程式碼以及介面圖:

Socketdemoviewcontroller.h程式碼  收藏程式碼
  1. //  
  2. //  SocketDemoViewController.h  
  3. //  SocketDemo  
  4. //  
  5. //  Created by xiang xiva on 10-7-10.  
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.  
  7. //  
  8. #import <UIKit/UIKit.h>  
  9. #import "AsyncSocket.h"
  10. #define SRV_CONNECTED 0
  11. #define SRV_CONNECT_SUC 1
  12. #define SRV_CONNECT_FAIL 2
  13. #define HOST_IP @"192.168.110.1"
  14. #define HOST_PORT 8080
  15. @interface SocketDemoViewController : UIViewController {  
  16.     UITextField *inputMsg;  
  17.     UILabel *outputMsg;  
  18.     AsyncSocket *client;  
  19. }  
  20. @property (nonatomic, retain) AsyncSocket *client;  
  21. @property (nonatomic, retain) IBOutlet UITextField *inputMsg;  
  22. @property (nonatomic, retain) IBOutlet UILabel *outputMsg;  
  23. - (int) connectServer: (NSString *) hostIP port:(int) hostPort;  
  24. - (void) showMessage:(NSString *) msg;  
  25. - (IBAction) sendMsg;  
  26. - (IBAction) reConnect;  
  27. - (IBAction) textFieldDoneEditing:(id)sender;  
  28. - (IBAction) backgroundTouch:(id)sender;  
  29. @end  
 socketdemoviewcontroller.m程式碼  收藏程式碼
  1. //  
  2. //  SocketDemoViewController.m  
  3. //  SocketDemo  
  4. //  
  5. //  Created by xiang xiva on 10-7-10.  
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.  
  7. //  
  8. #import "SocketDemoViewController.h"
  9. @implementation SocketDemoViewController  
  10. @synthesize inputMsg, outputMsg;  
  11. @synthesize client;  
  12. /*  
  13. // The designated initializer. Override to perform setup that is required before the view is loaded.  
  14. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {  
  15.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  16.     if (self) {  
  17.         // Custom initialization  
  18.     }  
  19.     return self;  
  20. }  
  21. */  
  22. /*  
  23. // Implement loadView to create a view hierarchy programmatically, without using a nib.  
  24. - (void)loadView {  
  25. }  
  26. */  
  27. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  28. - (void)viewDidLoad {  
  29.     //[super viewDidLoad];  
  30.     [self connectServer:HOST_IP port:HOST_PORT];  
  31.     //監聽讀取  
  32. }  
  33. // Override to allow orientations other than the default portrait orientation.  
  34. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {  
  35.     return YES;  
  36. }  
  37. - (void)didReceiveMemoryWarning {  
  38.     // Releases the view if it doesn't have a superview.  
  39.     [super didReceiveMemoryWarning];  
  40.     // Release any cached data, images, etc that aren't in use.  
  41. }  
  42. - (void)viewDidUnload {  
  43.     self.client = nil;  
  44.     // Release any retained subviews of the main view.  
  45.     // e.g. self.myOutlet = nil;  
  46. }  
  47. - (int) connectServer: (NSString *) hostIP port:(int) hostPort{  
  48.     if (client == nil) {  
  49.         client = [[AsyncSocket alloc] initWithDelegate:self];  
  50.         NSError *err = nil;  
  51.         //192.168.110.128
  52.         if (![client connectToHost:hostIP onPort:hostPort error:&err]) {  
  53.             NSLog(@"%@ %@", [err code], [err localizedDescription]);  
  54.             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
  55.                                             stringByAppendingString:hostIP]   
  56.                                                             message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]   
  57.                                                            delegate:self   
  58.                                                   cancelButtonTitle:@"OK"
  59.                                                   otherButtonTitles:nil];  
  60.             [alert show];  
  61.             [alert release];  
  62.             //client = nil;  
  63.             return SRV_CONNECT_FAIL;  
  64.         } else {  
  65.             NSLog(@"Conectou!");  
  66.             return SRV_CONNECT_SUC;  
  67.         }  
  68.     }  
  69.     else {  
  70.         [client readDataWithTimeout:-1 tag:0];  
  71.         return SRV_CONNECTED;  
  72.     }  
  73. }  
  74. - (IBAction) reConnect{  
  75.     int stat = [self connectServer:HOST_IP port:HOST_PORT];  
  76.     switch (stat) {  
  77.         case SRV_CONNECT_SUC:  
  78.             [self showMessage:@"connect success"];  
  79.             break;  
  80.         case SRV_CONNECTED:  
  81.             [self showMessage:@"It's connected,don't agian"];  
  82.             break;  
  83.         default:  
  84.             break;  
  85.     }  
  86. }  
  87. - (IBAction) sendMsg{  
  88.     NSString *inputMsgStr = self.inputMsg.text;  
  89.     NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];  
  90.     NSLog(@"%a",content);  
  91.     NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];  
  92.     [client writeData:data withTimeout:-1 tag:0];  
  93.     //[data release];  
  94.     //[content release];  
  95.     //[inputMsgStr release];  
  96.     //繼續監聽讀取  
  97.     //[client readDataWithTimeout:-1 tag:0];  
  98. }  
  99. #pragma mark -  
  100. #pragma mark close Keyboard  
  101. - (IBAction) textFieldDoneEditing:(id)sender{  
  102.     [sender resignFirstResponder];  
  103. }  
  104. - (IBAction) backgroundTouch:(id)sender{  
  105.     [inputMsg resignFirstResponder];  
  106. }  
  107. #pragma mark socket uitl  
  108. - (void) showMessage:(NSString *) msg{  
  109.     UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
  110.                                                     message:msg  
  111.                                                    delegate:nil