转载自 http://blog.youkuaiyun.com/jeepxiaozi/article/details/9154925
今天我们来学习下如何在IOS中使用socket连接,幸运的是,感谢github,我们找到一个第三方的开源类库可以很方便的帮我们实现这个,接下来我们就来实现一下,不过这次虽然有图形界面,但我们没有添加任何东西。
首先说一下这里server端是用python写的,简单的写了一个,代码如下:
- #!/usr/bin/env python
- #-*-coding:utf-8-*-
- import socket
- def getInfo():
- address=('127.0.0.1',8888)
- sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- sock.bind(address)
- sock.listen(5)
- client,addr=sock.accept()
- print 'connected with',addr
- client.send(b'Hi there')
- ra=sock.recv(1024)
- print ra
- client.close()
- sock.close()
- #end def
- if __name__=='__main__':
- getInfo()
因为mac系统下默认是安装了python的,正好也能把python练习一下,活学活用。
然后说下我们使用的第三方库,AsyncSocket ,那么我们去git上把它clone出来。
接着我们就开始写IOS端了,首先新建一个项目,添加CFNetwork.framework到项目中。
然后在我们的项目中把AsyncSocket添加进来:
然后我们在ETViewController.h中添加以下代码:
- #import <UIKit/UIKit.h>
- #import "AsyncSocket.h"
- @interface ETViewController : UIViewController
- {
- AsyncSocket *asyncSocket;
- }
- #import "ETViewController.h"
- @interface ETViewController ()
- @end
- @implementation ETViewController
- - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
- {
- self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
- if (self) {
- // Custom initialization
- }
- return self;
- }
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
- NSError *err = nil;
- if(![asyncSocket connectToHost:@"127.0.0.1" onPort:8888 error:&err])
- {
- NSLog(@"Error: %@", err);
- }
- }
- //建立连接
- -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
- {
- NSLog(@"onScoket:%p did connecte to host:%@ on port:%d",sock,host,port);
- [sock readDataWithTimeout:1 tag:0];
- }
- //读取数据
- -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
- {
- NSString *aStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"aStr==%@",aStr);
- [aStr release];
- NSData *aData=[@"Hi there" dataUsingEncoding:NSUTF8StringEncoding];
- [sock writeData:aData withTimeout:-1 tag:1];
- [sock readDataWithTimeout:1 tag:0];
- }
- //是否加密
- -(void)onSocketDidSecure:(AsyncSocket *)sock
- {
- NSLog(@"onSocket:%p did go a secure line:YES",sock);
- }
- //遇到错误时关闭连接
- -(void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
- {
- NSLog(@"onSocket:%p will disconnect with error:%@",sock,err);
- }
- //断开连接
- -(void)onSocketDidDisconnect:(AsyncSocket *)sock
- {
- NSLog(@"onSocketDidDisconnect:%p",sock);
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- -(void)dealloc
- {
- [asyncSocket release];
- [super dealloc];
- }
- @end
这些完成了之后呢,我们就可以开始测试了,那么首先要启动python写的server,进入终端,进入到pyServer.py所在的目录,然后输入如下命令来启动server:
- python pyServer.py
之后回车,server就启动了,然后我们就可以启动IOS模拟器来进行调试了,可以收到如下图所示的回应信息,说明我们成功了:
OK,今天的知识就学到这里,那么随着时间的积累,同时自己也在学Tornado,那么希望可以用python为IOS写出更好的服务端。