iOS Socket第三方开源类库 AsyncSocket

假如你也是一个java程序员,而你又不是很懂Socket。

下面我的这篇文章也许能帮助你一些。

http://xiva.iteye.com/blog/993336


首先我们写好上面文章中的server端。

下面我们可以访问一下下面的地址:


http://code.google.com/p/cocoaasyncsocket/

这是一个开源框架。呵,不知道拿到自己程序中使用是否涉及侵权。

但是这句话“The CocoaAsyncSocket project is in the public domain.”是我有信心使用它们的源码,否则只能自己用c来写了,或者使用CFSocket、CFNetwork等类自己来写了。不过也无妨,应在在使用线程的情况下,我们也是可以实现的。


总之,为了开发的便捷,我使用了AsyncSocket这个类,这样可以异步通信。


建立一个基于视图的应用程序,按照http://code.google.com/p/cocoaasyncsocket/wiki/Reference_AsyncSocket

我们AsyncSocket.h和AsyncSocket.m到我们的项目中,并且导入CFNetwork.framework。这样基本准备工作就做好了。

下面提供我的应用中的代码以及界面图:

Socketdemoviewcontroller.h代码iOS Socket第三方开源类库 AsyncSocket
  1. //
  2. //SocketDemoViewController.h
  3. //SocketDemo
  4. //
  5. //Createdbyxiangxivaon10-7-10.
  6. //Copyright2010__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import<UIKit/UIKit.h>
  9. #import"AsyncSocket.h"
  10. #defineSRV_CONNECTED0
  11. #defineSRV_CONNECT_SUC1
  12. #defineSRV_CONNECT_FAIL2
  13. #[email protected]"192.168.110.1"
  14. #defineHOST_PORT8080
  15. @interfaceSocketDemoViewController:UIViewController{
  16. UITextField*inputMsg;
  17. UILabel*outputMsg;
  18. AsyncSocket*client;
  19. }
  20. @property(nonatomic,retain)AsyncSocket*client;
  21. @property(nonatomic,retain)IBOutletUITextField*inputMsg;
  22. @property(nonatomic,retain)IBOutletUILabel*outputMsg;
  23. -(int)connectServer:(NSString*)hostIPport:(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代码iOS Socket第三方开源类库 AsyncSocket
  1. //
  2. //SocketDemoViewController.m
  3. //SocketDemo
  4. //
  5. //Createdbyxiangxivaon10-7-10.
  6. //Copyright2010__MyCompanyName__.Allrightsreserved.
  7. //
  8. #import"SocketDemoViewController.h"
  9. @implementationSocketDemoViewController
  10. @synthesizeinputMsg,outputMsg;
  11. @synthesizeclient;
  12. /*
  13. //Thedesignatedinitializer.Overridetoperformsetupthatisrequiredbeforetheviewisloaded.
  14. -(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{
  15. self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];
  16. if(self){
  17. //Custominitialization
  18. }
  19. returnself;
  20. }
  21. */
  22. /*
  23. //ImplementloadViewtocreateaviewhierarchyprogrammatically,withoutusinganib.
  24. -(void)loadView{
  25. }
  26. */
  27. //ImplementviewDidLoadtodoadditionalsetupafterloadingtheview,typicallyfromanib.
  28. -(void)viewDidLoad{
  29. //[superviewDidLoad];
  30. [selfconnectServer:HOST_IPport:HOST_PORT];
  31. //监听读取
  32. }
  33. //Overridetoalloworientationsotherthanthedefaultportraitorientation.
  34. -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
  35. returnYES;
  36. }
  37. -(void)didReceiveMemoryWarning{
  38. //Releasestheviewifitdoesn'thaveasuperview.
  39. [superdidReceiveMemoryWarning];
  40. //Releaseanycacheddata,images,etcthataren'tinuse.
  41. }
  42. -(void)viewDidUnload{
  43. self.client=nil;
  44. //Releaseanyretainedsubviewsofthemainview.
  45. //e.g.self.myOutlet=nil;
  46. }
  47. -(int)connectServer:(NSString*)hostIPport:(int)hostPort{
  48. if(client==nil){
  49. client=[[AsyncSocketalloc]initWithDelegate:self];
  50. NSError*err=nil;
  51. //192.168.110.128
  52. if(![clientconnectToHost:hostIPonPort:hostPorterror:&err]){
  53. NSLog(@"%@%@",[errcode],[errlocalizedDescription]);
  54. UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:[@"Connectionfailedtohost"
  55. stringByAppendingString:hostIP]
  56. message:[[[NSStringalloc]initWithFormat:@"%@",[errcode]]stringByAppendingString:[errlocalizedDescription]]
  57. delegate:self
  58. cancelButtonTitle:@"OK"
  59. otherButtonTitles:nil];
  60. [alertshow];
  61. [alertrelease];
  62. //client=nil;
  63. returnSRV_CONNECT_FAIL;
  64. }else{
  65. NSLog(@"Conectou!");
  66. returnSRV_CONNECT_SUC;
  67. }
  68. }
  69. else{
  70. [clientreadDataWithTimeout:-1tag:0];
  71. returnSRV_CONNECTED;
  72. }
  73. }
  74. -(IBAction)reConnect{
  75. intstat=[selfconnectServer:HOST_IPport:HOST_PORT];
  76. switch(stat){
  77. caseSRV_CONNECT_SUC:
  78. [selfshowMessage:@"connectsuccess"];
  79. break;
  80. caseSRV_CONNECTED:
  81. [selfshowMessage:@"It'sconnected,don'tagian"];
  82. break;
  83. default:
  84. break;
  85. }
  86. }
  87. -(IBAction)sendMsg{
  88. NSString*inputMsgStr=self.inputMsg.text;
  89. NSString*content=[inputMsgStrstringByAppendingString:@"\r\n"];
  90. NSLog(@"%a",content);
  91. NSData*data=[contentdataUsingEncoding:NSISOLatin1StringEncoding];
  92. [clientwriteData:datawithTimeout:-1tag:0];
  93. //[datarelease];
  94. //[contentrelease];
  95. //[inputMsgStrrelease];
  96. //继续监听读取
  97. //[clientreadDataWithTimeout:-1tag:0];
  98. }
  99. #pragmamark-
  100. #pragmamarkcloseKeyboard
  101. -(IBAction)textFieldDoneEditing:(id)sender{
  102. [senderresignFirstResponder];
  103. }
  104. -(IBAction)backgroundTouch:(id)sender{
  105. [inputMsgresignFirstResponder];
  106. }
  107. #pragmamarksocketuitl
  108. -(void)showMessage:(NSString*)msg{
  109. UIAlertView*alert=[[UIAlertViewalloc]initWithTitle:@"Alert!"
  110. message:msg
  111. delegate:nil
  112. cancelButtonTitle:@"OK"
  113. otherButtonTitles:nil];
  114. [alertshow];
  115. [alertrelease];
  116. }
  117. #pragmamarksocketdelegate
  118. -(void)onSocket:(AsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(UInt16)port{
  119. [clientreadDataWithTimeout:-1tag:0];
  120. }
  121. -(void)onSocket:(AsyncSocket*)sockwillDisconnectWithError:(NSError*)err
  122. {
  123. NSLog(@"Error");
  124. }
  125. -(void)onSocketDidDisconnect:(AsyncSocket*)sock
  126. {
  127. NSString*[email protected]"Sorrythisconnectisfailure";
  128. [selfshowMessage:msg];
  129. [msgrelease];
  130. client=nil;
  131. }
  132. -(void)onSocketDidSecure:(AsyncSocket*)sock{
  133. }
  134. -(void)onSocket:(AsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{
  135. NSString*aStr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
  136. NSLog(@"Havareceiveddatasis:%@",aStr);
  137. self.outputMsg.text=aStr;
  138. [aStrrelease];
  139. [clientreadDataWithTimeout:-1tag:0];
  140. }
  141. #pragmamarkdealloc
  142. -(void)dealloc{
  143. [clientrelease];
  144. [inputMsgrelease];
  145. [outputMsgrelease];
  146. [superdealloc];
  147. }
  148. @end

还是先给出我的界面吧,否则很难懂这些代码

iOS Socket第三方开源类库 AsyncSocket

这样大家满意了吧!


好了说了这么多我们还是来看看代码究竟怎么回事吧。

首先从头文件开始看吧,

1,导入头文件#import "AsyncSocket.h",然后是一些宏

2,声明一个AsyncSocket对象,其他就是一些IBoutlet

再次我们看看视图加载,

Java代码iOS Socket第三方开源类库 AsyncSocket
  1. -(void)viewDidLoad{
  2. //[superviewDidLoad];
  3. [selfconnectServer:HOST_IPport:HOST_PORT];
  4. //监听读取
  5. }
显然我们调用了connectServer::这个方法。

在这个方法中,首先初始化我们的对象,使用代理的方式。对象显示是self。然后我们便需在我们的类中实现它的各种方法,来得到各种我们想得到的。

client = [[AsyncSocket alloc] initWithDelegate:self];


下面就是连接服务器了,

[client connectToHost:hostIP onPort:hostPort error:&err]


并且当client不为空时,我们就读取服务器的信息

[client readDataWithTimeout:-1 tag:0];

Java代码iOS Socket第三方开源类库 AsyncSocket
  1. -(void)onSocket:(AsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{
  2. NSString*aStr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
  3. NSLog(@"Havareceiveddatasis:%@",aStr);
  4. self.outputMsg.text=aStr;
  5. [aStrrelease];
  6. [clientreadDataWithTimeout:-1tag:0];
  7. }

在这个方法中很耐人寻味,主要就是在于递归的调用。

Sendmsg代码iOS Socket第三方开源类库 AsyncSocket
  1. -(IBAction)sendMsg{
  2. NSString*inputMsgStr=self.inputMsg.text;
  3. NSString*content=[inputMsgStrstringByAppendingString:@"\r\n"];
  4. NSLog(@"%a",content);
  5. NSData*data=[contentdataUsingEncoding:NSISOLatin1StringEncoding];
  6. [clientwriteData:datawithTimeout:-1tag:0];
  7. }

我们在看看上面发送消息的代码,中的在于"\r\n"的拼接,否则在java端的程序,无法知道你发过来的信息是否结束,当然你也可以使用其他的方式来读取客户端,比如定时;但是我在java端写的server是readLine来判断的,所以需要拼接这个\r\n.


其他的代码除了asyncSocket代理外都是我们所熟悉的。

这些都是asyncsocket代理的代码iOS Socket第三方开源类库 AsyncSocket
  1. -(void)onSocket:(AsyncSocket*)sockdidConnectToHost:(NSString*)hostport:(UInt16)port{
  2. [clientreadDataWithTimeout:-1tag:0];
  3. }
  4. -(void)onSocket:(AsyncSocket*)sockwillDisconnectWithError:(NSError*)err
  5. {
  6. NSLog(@"Error");
  7. }
  8. -(void)onSocketDidDisconnect:(AsyncSocket*)sock
  9. {
  10. NSString*[email protected]"Sorrythisconnectisfailure";
  11. [selfshowMessage:msg];
  12. [msgrelease];
  13. client=nil;
  14. }
  15. -(void)onSocketDidSecure:(AsyncSocket*)sock{
  16. }
  17. -(void)onSocket:(AsyncSocket*)sockdidReadData:(NSData*)datawithTag:(long)tag{
  18. NSString*aStr=[[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
  19. NSLog(@"Havareceiveddatasis:%@",aStr);
  20. self.outputMsg.text=aStr;
  21. [aStrrelease];
  22. [clientreadDataWithTimeout:-1tag:0];
  23. }

到此就结束了。