我尝试使用GCDAsyncSocket
连接到WHOIS服务器(com.whois-servers.net:43)。我可以连接并写入服务器,didWriteDataWithTag:
被调用,但没有数据。 WHOIS服务器确实发送了响应,但我无法读取它。
NSLog(@"Connecting to \"%@\" on port %hu...", host, port);
self.viewController.label.text = @"Connecting...";
NSError *error = nil;
if (![asyncSocket connectToHost:@"com.whois-servers.net" onPort:43 error:&error])
{
DDLogError(@"Error connecting: %@", error);
self.viewController.label.text = @"Oops";
}
NSString *requestStr = [NSString stringWithFormat:@"domain google.com\r\n\r\n"];
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:requestData withTimeout:-1 tag:0];
[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];
以下是didReadData:
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
DDLogInfo(@"socket:%p didReadData:withTag:%d", sock, tag);
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Data: %i", [data length]);
}
帮助?!
答案 0 :(得分:0)
我使用AsyncSocket遇到了同样的问题。我从来没有完全解决它,但找到了一个紧密的解决方案。
在 onSocket:willDisconnectWithError (GapSocketCommand.m)中,通过调用unreadData,可以在连接失败时获取当前缓冲区。
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"onSocket:willDisconnectWithError %@",err);
NSData * unreadData = [sock unreadData]; // ** This gets the current buffer
if(unreadData) {
[self onSocket:sock didReadData:unreadData withTag:NULL]; // ** Return as much data that could be collected
} else {
NSString* jsString = [[NSString alloc] initWithFormat:@"GapSocket.__onError(\"%d\",\"%@\");"
,[sock userData]
,[err localizedDescription] ];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
//[jsString release];
}
}
您必须修改它以应用于GCDAsyncSocket,但解决方案应该是相同的。