使用开源代码Asyncsocket进行socket编程

 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];


在iphone的平台下,要进行socket开发其实有很多种的方法,开源的库Asyncsocket,官方的CFSocket,还有BSD的socket。

下面是用开源的库Asyncsocket的例子:

[java]  view plain copy
  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.   
  9. #import <UIKit/UIKit.h>  
  10. #import "AsyncSocket.h"  
  11. #define SRV_CONNECTED 0  
  12. #define SRV_CONNECT_SUC 1  
  13. #define SRV_CONNECT_FAIL 2  
  14. #define HOST_IP @"192.168.110.1"  
  15. #define HOST_PORT 8080  
  16.   
  17. @interface SocketDemoViewController : UIViewController {  
  18.    
  19.  UITextField *inputMsg;  
  20.  UILabel *outputMsg;  
  21.  AsyncSocket *client;  
  22. }  
  23.   
  24. @property (nonatomic, retain) AsyncSocket *client;  
  25. @property (nonatomic, retain) IBOutlet UITextField *inputMsg;  
  26. @property (nonatomic, retain) IBOutlet UILabel *outputMsg;  
  27.   
  28. - (int) connectServer: (NSString *) hostIP port:(int) hostPort;  
  29. - (void) showMessage:(NSString *) msg;  
  30. - (IBAction) sendMsg;  
  31. - (IBAction) reConnect;  
  32. - (IBAction) textFieldDoneEditing:(id)sender;  
  33. - (IBAction) backgroundTouch:(id)sender;  
  34.   
  35. @end  
  36.   
  37.    
  38.   
  39. //  
  40. //  SocketDemoViewController.m  
  41. //  SocketDemo  
  42. //  
  43. //  Created by xiang xiva on 10-7-10.  
  44. //  Copyright 2010 __MyCompanyName__. All rights reserved.  
  45. //  
  46.   
  47. #import "SocketDemoViewController.h"  
  48.   
  49. @implementation SocketDemoViewController  
  50.   
  51. @synthesize inputMsg, outputMsg;  
  52. @synthesize client;  
  53. /* 
  54. // The designated initializer. Override to perform setup that is required before the view is loaded. 
  55. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
  56.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
  57.     if (self) { 
  58.         // Custom initialization 
  59.     } 
  60.     return self; 
  61. } 
  62. */  
  63.   
  64. /* 
  65. // Implement loadView to create a view hierarchy programmatically, without using a nib. 
  66. - (void)loadView { 
  67. } 
  68. */  
  69.   
  70.    
  71.   
  72. // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  
  73. - (void)viewDidLoad {  
  74.     //[super viewDidLoad];  
  75.  [self connectServer:HOST_IP port:HOST_PORT];  
  76.  //监听读取  
  77.    
  78. }  
  79.   
  80.    
  81.   
  82. // Override to allow orientations other than the default portrait orientation.  
  83. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {  
  84.     return YES;  
  85. }  
  86.   
  87. - (void)didReceiveMemoryWarning {  
  88.  // Releases the view if it doesn't have a superview.  
  89.     [super didReceiveMemoryWarning];  
  90.    
  91.  // Release any cached data, images, etc that aren't in use.  
  92. }  
  93.   
  94. - (void)viewDidUnload {  
  95.  self.client = nil;  
  96.  // Release any retained subviews of the main view.  
  97.  // e.g. self.myOutlet = nil;  
  98. }  
  99.   
  100. - (int) connectServer: (NSString *) hostIP port:(int) hostPort{  
  101.    
  102.  if (client == nil) {  
  103.   client = [[AsyncSocket alloc] initWithDelegate:self];  
  104.   NSError *err = nil;  
  105.   //192.168.110.128  
  106.   if (![client connectToHost:hostIP onPort:hostPort error:&err]) {  
  107.    NSLog(@"%@ %@", [err code], [err localizedDescription]);  
  108.      
  109.    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "  
  110.            stringByAppendingString:hostIP]  
  111.                message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]  
  112.                  delegate:self  
  113.               cancelButtonTitle:@"OK"  
  114.               otherButtonTitles:nil];  
  115.    [alert show];  
  116.    [alert release];  
  117.    //client = nil;  
  118.    return SRV_CONNECT_FAIL;  
  119.   } else {  
  120.    NSLog(@"Conectou!");  
  121.    return SRV_CONNECT_SUC;  
  122.   }  
  123.  }  
  124.  else {  
  125.   [client readDataWithTimeout:-1 tag:0];  
  126.   return SRV_CONNECTED;  
  127.  }  
  128.    
  129. }  
  130.   
  131. - (IBAction) reConnect{  
  132.  int stat = [self connectServer:HOST_IP port:HOST_PORT];  
  133.  switch (stat) {  
  134.   case SRV_CONNECT_SUC:  
  135.    [self showMessage:@"connect success"];  
  136.    break;  
  137.   case SRV_CONNECTED:  
  138.    [self showMessage:@"It's connected,don't agian"];  
  139.    break;  
  140.   default:  
  141.    break;  
  142.  }  
  143. }  
  144.   
  145. - (IBAction) sendMsg{  
  146.    
  147.  NSString *inputMsgStr = self.inputMsg.text;  
  148.  NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];  
  149.  NSLog(@"%a",content);  
  150.  NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];  
  151.  [client writeData:data withTimeout:-1 tag:0];  
  152.    
  153.  //[data release];  
  154.  //[content release];  
  155.  //[inputMsgStr release];  
  156.  //继续监听读取  
  157.  //[client readDataWithTimeout:-1 tag:0];  
  158. }  
  159.   
  160. #pragma mark -  
  161. #pragma mark close Keyboard  
  162. - (IBAction) textFieldDoneEditing:(id)sender{  
  163.  [sender resignFirstResponder];  
  164. }  
  165.   
  166. - (IBAction) backgroundTouch:(id)sender{  
  167.  [inputMsg resignFirstResponder];  
  168. }  
  169.   
  170. #pragma mark socket uitl  
  171.   
  172. - (void) showMessage:(NSString *) msg{  
  173.  UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"  
  174.                                                     message:msg  
  175.                                                    delegate:nil  
  176.                                           cancelButtonTitle:@"OK"  
  177.                                           otherButtonTitles:nil];  
  178.     [alert show];  
  179.     [alert release];  
  180. }  
  181.   
  182.   
  183. #pragma mark socket delegate  
  184.   
  185. - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{  
  186.  [client readDataWithTimeout:-1 tag:0];  
  187. }  
  188.   
  189. - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err  
  190. {  
  191.     NSLog(@"Error");  
  192. }  
  193.   
  194. - (void)onSocketDidDisconnect:(AsyncSocket *)sock  
  195. {  
  196.  NSString *msg = @"Sorry this connect is failure";  
  197.  [self showMessage:msg];  
  198.  [msg release];  
  199.  client = nil;  
  200. }  
  201.   
  202. - (void)onSocketDidSecure:(AsyncSocket *)sock{  
  203.    
  204. }  
  205.   
  206. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{  
  207.    
  208.  NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  209.  NSLog(@"Hava received datas is :%@",aStr);  
  210.  self.outputMsg.text = aStr;  
  211.  [aStr release];  
  212.  [client readDataWithTimeout:-1 tag:0];  
  213. }  
  214.   
  215. #pragma mark dealloc  
  216.   
  217. - (void)dealloc {  
  218.    
  219.  [client release];  
  220.  [inputMsg release];  
  221.  [outputMsg release];  
  222.     [super dealloc];  
  223. }  
  224.   
  225. @end  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值