IOS 开源库 asyncSocket 的使用心得

1.得到asyncSocket的代码

2.导入CFNetwork.framework

 

 

3.在.m中在代码中添加

 - (IBAction)pressTest:(id)sender { if (!_asyncSocket) { _asyncSocket = [[AsyncSocket alloc]initWithDelegate:self]; NSString *host = @"192.168.18.78"; int nPort = 9000; NSError *error = nil; //[_asyncSocket connectToHost:host onPort:nPort error:&error]; [_asyncSocket connectToHost:host onPort:nPort withTimeout:2 error:&error]; NSLog(@"%@",error); } }

 

在[_asyncSocket connectToHost:host onPort:nPort error:&error]; 和 [_asyncSocket connectToHost:host onPort:nPort withTimeout:2 error:&error];

建议选择后者,因为连接服务器有一个超时可以设置,可以更加灵活操作。超时后会调用

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err { NSLog(@"Info___willDisconnectWithError"); //[self logInfo:FORMAT(@"Client Disconnected: %@:%hu", [sock connectedHost], [sock connectedPort])]; [_asyncSocket release]; _asyncSocket = nil; }

 

 

收发数据中必须注意是添加 [sock readDataWithTimeout:-1 tag:0];否则接收不到数据,并且这个函数在数据返回就必须调用一次,让他一直循环下去。

比如在网络连接成功后

 

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { NSLog(@"Info___didConnectToHost"); [sock readDataWithTimeout:-1 tag:0]; }  

 

或者是收到数据后

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSLog(@"Info___didReadData"); NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])]; NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease]; if(msg) { NSLog(@"%@",msg); } else { [self logError:@"Error converting received data into UTF-8 String"]; } [sock readDataWithTimeout:-1 tag:0]; } 

 

其他的下次再遇到问题后在补充
 

你可能感兴趣的:(ios,String,网络,服务器,encoding)