Socket连接实例

转载自 http://blog.youkuaiyun.com/jeepxiaozi/article/details/9154925

今天我们来学习下如何在IOS中使用socket连接,幸运的是,感谢github,我们找到一个第三方的开源类库可以很方便的帮我们实现这个,接下来我们就来实现一下,不过这次虽然有图形界面,但我们没有添加任何东西。

首先说一下这里server端是用python写的,简单的写了一个,代码如下:

[python]  view plain copy
  1. #!/usr/bin/env python  
  2. #-*-coding:utf-8-*-  
  3.   
  4. import socket  
  5. def getInfo():  
  6.     address=('127.0.0.1',8888)  
  7.     sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  
  8.     sock.bind(address)  
  9.     sock.listen(5)  
  10.       
  11.     client,addr=sock.accept()  
  12.     print 'connected with',addr  
  13.       
  14.     client.send(b'Hi there')  
  15.     ra=sock.recv(1024)  
  16.     print ra  
  17.       
  18.     client.close()  
  19.     sock.close()  
  20. #end def  
  21.   
  22. if __name__=='__main__':  
  23.     getInfo()  

因为mac系统下默认是安装了python的,正好也能把python练习一下,活学活用。

然后说下我们使用的第三方库,AsyncSocket ,那么我们去git上把它clone出来。

接着我们就开始写IOS端了,首先新建一个项目,添加CFNetwork.framework到项目中。

然后在我们的项目中把AsyncSocket添加进来:


然后我们在ETViewController.h中添加以下代码:

[cpp]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2. #import "AsyncSocket.h"  
  3.   
  4. @interface ETViewController : UIViewController  
  5. {  
  6.     AsyncSocket *asyncSocket;  
  7. }  
接下来是ETViewController.m中的代码:

[cpp]  view plain copy
  1. #import "ETViewController.h"  
  2.   
  3. @interface ETViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ETViewController  
  8.   
  9. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  10. {  
  11.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  12.     if (self) {  
  13.         // Custom initialization  
  14.     }  
  15.     return self;  
  16. }  
  17.   
  18. - (void)viewDidLoad  
  19. {  
  20.     [super viewDidLoad];  
  21.     asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];  
  22.     NSError *err = nil;  
  23.     if(![asyncSocket connectToHost:@"127.0.0.1" onPort:8888 error:&err])  
  24.     {  
  25.         NSLog(@"Error: %@", err);  
  26.     }  
  27. }  
  28. //建立连接  
  29. -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port  
  30. {  
  31.     NSLog(@"onScoket:%p did connecte to host:%@ on port:%d",sock,host,port);  
  32.     [sock readDataWithTimeout:1 tag:0];  
  33. }  
  34.   
  35. //读取数据  
  36. -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag  
  37. {  
  38.     NSString *aStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  39.     NSLog(@"aStr==%@",aStr);  
  40.     [aStr release];  
  41.     NSData *aData=[@"Hi there" dataUsingEncoding:NSUTF8StringEncoding];  
  42.     [sock writeData:aData withTimeout:-1 tag:1];  
  43.     [sock readDataWithTimeout:1 tag:0];  
  44. }  
  45.   
  46. //是否加密  
  47. -(void)onSocketDidSecure:(AsyncSocket *)sock  
  48. {  
  49.     NSLog(@"onSocket:%p did go a secure line:YES",sock);  
  50. }  
  51.   
  52. //遇到错误时关闭连接  
  53. -(void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err  
  54. {  
  55.     NSLog(@"onSocket:%p will disconnect with error:%@",sock,err);  
  56. }  
  57.   
  58. //断开连接  
  59. -(void)onSocketDidDisconnect:(AsyncSocket *)sock  
  60. {  
  61.     NSLog(@"onSocketDidDisconnect:%p",sock);  
  62. }  
  63.   
  64. - (void)didReceiveMemoryWarning  
  65. {  
  66.     [super didReceiveMemoryWarning];  
  67.     // Dispose of any resources that can be recreated.  
  68. }  
  69. -(void)dealloc  
  70. {  
  71.     [asyncSocket release];  
  72.     [super dealloc];  
  73. }  
  74. @end  

这些完成了之后呢,我们就可以开始测试了,那么首先要启动python写的server,进入终端,进入到pyServer.py所在的目录,然后输入如下命令来启动server:

[python]  view plain copy
  1. python pyServer.py  

之后回车,server就启动了,然后我们就可以启动IOS模拟器来进行调试了,可以收到如下图所示的回应信息,说明我们成功了:


OK,今天的知识就学到这里,那么随着时间的积累,同时自己也在学Tornado,那么希望可以用python为IOS写出更好的服务端。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值