我正在尝试使用GCDAsyncSocket连接到WHOIS服务器(com.whis-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]);
}帮忙?!
发布于 2012-03-02 23:09:56
我在使用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,但解决方案应该是相同的。
https://stackoverflow.com/questions/8336300
复制相似问题