守望远方

热爱生活 热爱工作 守望远方
AsyncSocket编程
摘要: IOS实例 实现基于Socket TCP/IP通讯是本文要介绍的内容,之前写过基于http的网络传输层的通讯,现在项目需要实现tcp/ip的通讯协议,通过网络查找了一下,已经有人写好了公开的类库AsyncSocket,下面介绍一下AsyncSoc ...
 
 
       

IOS实例 实现基于Socket TCP/IP通讯是本文要介绍的内容,之前写过基于http的网络传输层的通讯,现在项目需要实现tcp/ip的通讯协议,通过网络查找了一下,已经有人写好了公开的类库AsyncSocket,下面介绍一下AsyncSocket的使用方法。可以参考AsyncSocket的官方文档。

使用方法如下:

1、创建工程。

2、把AsyncSocket添加到项目中。

3、添加CFNetwork.framework到工程中。

4、实现测试类:

  1. #import <UIKit/UIKit.h>   
  2. #import "AsyncSocket.h"   
  3. @interface iphone_socketViewController : UIViewController {   
  4.  
  5.     AsyncSocket *asyncSocket;   
  6. }   
  7.  
  8. @end 

相应的方法实现:

  1. #import "iphone_socketViewController.h"   
  2. @implementation iphone_socketViewController   
  3. - (void)viewDidLoad {   
  4.     [super viewDidLoad];   
  5.     asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];   
  6.     NSError *err = nil;   
  7.    if(![asyncSocket connectToHost:@"192.168.0.113" onPort:25001 error:&err])   
  8.     {   
  9.         NSLog(@"Error: %@", err);   
  10.     }   
  11. }   
  12. - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port   
  13. {   
  14.     NSLog(@"onSocket:%p didConnectToHost:%@ port:%hu", sock, host, port);   
  15.     [sock readDataWithTimeout:1 tag:0];   
  16. }   
  17. -(void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag   
  18. {   
  19.     NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];   
  20.     NSLog(@"===%@",aStr);   
  21.     [aStr release];   
  22.     NSData* aData= [@"<xml>我喜欢你<xml>" dataUsingEncoding: NSUTF8StringEncoding];   
  23.     [sock writeData:aData withTimeout:-1 tag:1];   
  24.     [sock readDataWithTimeout:1 tag:0];   
  25. }   
  26. - (void)onSocket:(AsyncSocket *)sock didSecure:(BOOL)flag   
  27. {   
  28.         NSLog(@"onSocket:%p didSecure:YES", sock);   
  29. }   
  30. - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err   
  31. {   
  32.     NSLog(@"onSocket:%p willDisconnectWithError:%@", sock, err);   
  33. }   
  34. - (void)onSocketDidDisconnect:(AsyncSocket *)sock   
  35. {   
  36.     //断开连接了   
  37.     NSLog(@"onSocketDidDisconnect:%p", sock);   
  38. }   
  39. - (void)didReceiveMemoryWarning {   
  40.     [super didReceiveMemoryWarning];   
  41. }   
  42. - (void)viewDidUnload {   
  43.     asyncSocket=nil;   
  44. }   
  45. - (void)dealloc {   
  46.     [asyncSocket release];   
  47.     [super dealloc];   
  48. }   
  49. @end 

这里只实现了简单的客户端,关于服务器的实现,是采用pathy写的。在源代码中有。

编译运行结果:

服务器端:

  1. bogon:iosworkspace vsp$ ./Servers.py  

客户端的IP是: (’192.168.0.169′, 54851)

posted on 2012-12-18 11:06  守望远方  阅读(864)  评论(0编辑  收藏  举报