Socket编程——第三方类库 AsyncSocket
2015-12-04 21:49
323 查看
在这里,是调用第三方的一个开源类库来实现Socket编程。网址为:http://code.google.com/p/cocoaasyncsocket/。
一,导入ASyncSocket库
将下载下来的文件中,Source文件夹里面的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四个文件复制到你的工程里面。然后工程中加入一个类库CFNetwork.framework,
二,客户端的程序
1,导入.h文件并定义AsyncSocket对象
2,在viewDidLoad中进行监听读取
3,链接服务器
4,连接成功和连接失败的函数
5,读取数据
6,写数据
一,导入ASyncSocket库
将下载下来的文件中,Source文件夹里面的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四个文件复制到你的工程里面。然后工程中加入一个类库CFNetwork.framework,
二,客户端的程序
1,导入.h文件并定义AsyncSocket对象
#import "AsyncSocket.h" @property (nonatomic, retain) AsyncSocket *client;
2,在viewDidLoad中进行监听读取
[self connectServer:HOST_IP port:HOST_PORT];
3,链接服务器
- (int) connectServer: (NSString *) hostIP port:(int) hostPort{ if (client == nil) { client = [[AsyncSocket alloc]initWithDelegate:self]; NSError *err = nil; if (![client connectToHost:hostIP onPort:hostPort error:&err]) { NSLog(@"%ld %@", (long)[err code], [err localizedDescription]); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host " stringByAppendingString:hostIP] message:[[[NSString alloc]initWithFormat:@"%ld",(long)[err code]] stringByAppendingString:[err localizedDescription]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; return SRV_CONNECT_FAIL; } else { return SRV_CONNECT_SUC; } } else { [client readDataWithTimeout:-1 tag:0]; return SRV_CONNECTED; } }
4,连接成功和连接失败的函数
//连接成功后读取数据 - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{ [client readDataWithTimeout:-1 tag:0]; } //连接失败则返回error - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err { NSLog(@"Error"); } - (void)onSocketDidDisconnect:(AsyncSocket *)sock { NSString *msg = @"Sorry this connect is failure"; [AlertView showNotice:msg]; client = nil; }
5,读取数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{ _aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Hava received datas is :%@",_aStr); flag = 1; [client readDataWithTimeout:-1 tag:0]; }
6,写数据
NSData *data0 = [@"1" dataUsingEncoding:NSUTF8StringEncoding]; [client writeData:data0 withTimeout:-1 tag:1];
相关文章推荐
- java-模拟tomcat服务器
- Linux socket 初步
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- 肯特·贝克:改变人生的代码整理魔法
- 你应该学习哪种编程语言?
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- java socket 注意的地方
- java socket 注意的地方
- [转]我们需要一种其他人能使用的编程语言
- DB2编程序技巧(1)
- DB2编程序技巧 (四)
- 女人VS编程_国庆快乐
- DB2编程序技巧 (六)
- DB2编程序技巧 (三)
- DB2编程序技巧 (九)