物联网通信第一天

 

IOS 用封装API AsyncSocket进行网络通信 



AsyncSocket是一个用Object-c封装好的网络通讯API,调用方便,容易实现

使用AsyncSocket可以很方便的与其它系统进行Socket通信, AsyncSocket包括TCP和UDP,通过实现委托AsyncSocketDelegate进行交互。

下面是TCP通讯

API 下载地址 :点击下载

首先,调用此API时需先引入CFNetWork.framework

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

闲话不多说,上代码:

SocketServer端代码:

.h文件

[cpp]  view plain copy
  1. @interface ViewController :UIViewController<AsyncSocketDelegate,UITextFieldDelegate>  
  2. {  
  3.     AsyncSocket *listener;//监听客户端请求  
  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文件

[cpp]  view plain copy
  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是否已经开始监听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(@"开始监听");  
  22.         isRunning = YES;  
  23.     }  
  24.     else  
  25.     {  
  26.         NSLog(@"重新监听");  
  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的个数  
  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.     //将连接服务的客户端记录起来,以便以后实现客户端通信时使用  
  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.     //向当前连接服务器的客户端发送连接成功信息  
  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.  读取客户端发送来的信息(收到socket信息时调用) 
  101.  **/  
  102. - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag  
  103. {  
  104.     NSString *msg = [[[NSStringalloc]initWithData: dataencoding:NSUTF8StringEncoding]autorelease];  
  105.     //获取当前发送消息的客户端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. //这里要说明一下,在想另外一个客户端发送信息时需要指定客户端ip地址,所以在发送消息的时候,应该将ip地址一并写在消息里面,然后由服务端进行处理,我这里这是做了一个简单的Demo,有2个客户端相互发送消息  
  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文件

[cpp]  view plain copy
  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文件

[cpp]  view plain copy
  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. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值