首先导入CFNetwork.framework框架
1、下载ASyncSocket库源码
2、把ASyncSocket库源码加入项目
3、在项目增加CFNetwork框架
使用AsyncSocket开源的框架可以很方便的与其它系统进行Socket通信, AsyncSocket包括TCP和UDP,
通过实现委托AsyncSocketDelegate进行交互。AsyncSocketDelegate有如下消息调用。
1 @implementation SocketComm
2
3 //初始话,创建socket
4 - (id) init
5 {
6 self = [super init];
7 if (self != nil) {
8 _sock = [[AsyncSocket alloc] initWithDelegate:self];
9 [_sock setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
10
11 }
12 return self;
13
14 }
即将连接及发生错误会调用willDisconnectWithError
1 - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err{
2
3 [_asyncSocket release];
4
5 _asyncSocket = nil;
6
7 }
其它方法调用:
1 - (void)onSocketDidDisconnect:(AsyncSocket *)sock;
2 //收到新的socket连接时调用
3 - (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket;
4
5 - (NSRunLoop *)onSocket:(AsyncSocket *)sock wantsRunLoopForNewSocket:(AsyncSocket *)newSocket;
6
7 - (BOOL)onSocketWillConnect:(AsyncSocket *)sock;
网络连接成功后,调用didConnectToHost, 收发数据中必须添加 [sock readDataWithTimeout:-1 tag:0];否则接收不到数据,
并且这个函数在数据返回就必须调用一次,让他一直循环下去
//异步返回的连接成功
1 - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
2 {
3
4 [sock readDataWithTimeout:-1 tag:0];
5
6 }
//读取客户端发送来的信息
1 - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
2 {
3
4 NSString *msg = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
5
6 if(msg)
7 {
8
9 //处理受到的数据
10
11 }
12 else
13 {
14
15 NSLog(@"Error converting received data into UTF-8 String");
16
17 }
18
19 [sock readDataWithTimeout:-1 tag:0];
20
21 }
1 - (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
2
3 - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;
4
5 - (void)onSocket:(AsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;
6
7 - (NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
8
9 bytesDone:(NSUInteger)length;
10
11 - (NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
12 bytesDone:(NSUInteger)length;
13
14 - (void)onSocketDidSecure:(AsyncSocket *)sock;
AsyncSocket包括connectToHost,writeData,readDataWithTimeout等基本调用,发送这些消息,会触发相应Delegate相应的方法。