============================================================
博文原创,转载请声明出处
============================================================
详解iPhone 下AsyncSocket网络库编程是本文要介绍的内容,iphone的标准推荐CFNetwork C库编程.但是编程比较烦躁。在其它OS往往用类来封装的对Socket函数的处理。比如MFC的CAsysncSocket.在iphone也有类似于开源项目.cocoa AsyncSocket库
ok,试试吧
官方网站:http://code.google.com/p/cocoaasyncsocket/
这里只上例子,自己在项目中使用的,绝对能使用,如果有疑问,欢迎留言讨论。
----------------
注意,CAsysncSocket已经将tcp、udp的连接异步化处理,所以你只管在主线程调用即可
将AsyncSocket.h AsyncSocket.m 导入到你的工程中,
在自己建立的util中,加入一下代码
#pragma mark tcp
- (void) connectToHost:(NSString*)host port:(int)port {
socket = [[AsyncSocket alloc] initWithDelegate:self]; //设置回调的delegate
//TODO 这里需要在退出局域网模式下断开
[socket disconnect]; //断开tcp连接
// socket
NSLog(@"tcp connecting to host:%@,port:%d",host,port);
@try {
[socket connectToHost:host onPort:port error:nil];
[socket readDataWithTimeout:-1 tag:1]; //这只超时,如果timeout为负数,则永远不超时
}
@catch (NSException *exception) { //异常处理
NSLog(@"connect exception %@,%@", [exception name], [exception description]);
}
}
//相应的回调函数
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
NSLog(@"did connect to host %@:%d", host, port);
}
- (void)sendMessage:(NSString*)msg {
NSLog(@"tcp send msg:%@", msg);
[socket readDataWithTimeout:SOCKET_TIMEOUT tag:1];
[socket writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:SOCKET_TIMEOUT tag:1];
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
NSString* message = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]autorelease];
NSLog(@"%f receive ReadData is: %@",[[NSDate date] timeIntervalSince1970],message);
}
-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
NSLog(@"onSocket:shouldTimeout-ReadWithTag:-----------");
return 0;
}
-(NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length{
NSLog(@"onSocket:shouldTimeout-WriteWithTag:-----------");
return 0;
}
-(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag{
NSLog(@"didWriteDataWithTag tag:%ld",tag);
}
-(void)onSocketDidDisconnect:(AsyncSocket *)sock{
NSLog(@"onSocketDidDisconnect sock:%@",sock);
[viewController onLocalDisconnect:0];
}
ok,试试吧