我一直在尝试对iPhone上的whois服务器执行whois查询。我尝试使用CFSocket,但放弃了它并试图用流做。代码:
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"whois.internic.net", 43, &readStream, &writeStream);
NSInputStream *is = (__bridge NSInputStream *)readStream;
NSOutputStream *os = (__bridge NSOutputStream *)writeStream;
[is scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[os scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[is open];
[os open];
NSString *msgtext = [[NSString alloc] initWithFormat:@"%@%d", @"domain www.google.com", '\n'];
NSData *data = [[NSData alloc] initWithData:[msgtext dataUsingEncoding:NSASCIIStringEncoding]];
[os write:[data bytes] maxLength:[data length]];
UInt8 buffer[1024];
int len;
NSLog(@"START LOOP");
BOOL b = [is hasBytesAvailable];
NSLog(@"%u", b);
while([is hasBytesAvailable]) //value = false
{
NSLog(@"HaveBytes");
len = [is read:buffer maxLength:sizeof(buffer)];
if(len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
NSLog(output);
}
}
似乎我的消息已发送,但我没有得到服务器的回复。尝试了几个服务器,但结果是一样的。为什么是这样?我发错了信息,我接受了错吗?它应该与流一起工作,因为我在Java中尝试过相同的工作。
请有人帮助我:(
编辑:
例如,我有一些Java代码,完美无缺:
import java.net.*;
import java.io.*;
public class WhoIs {
public static void main(String[] args) throws Exception{
Socket s = new Socket("whois.internic.net",43);
OutputStream os = s.getOutputStream();
String domain = "www.google.com"+"\n";
byte[] stringToByte = domain.getBytes();
os.write(stringToByte);
InputStream is = s.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
BufferedReader buf = new BufferedReader(reader);
String temp;
while((temp=buf.readLine())!=null){
System.out.println(temp);
}
}
}
Objective-c中的代码与此代码非常相似,但它不起作用。为什么呢?