0

我一直在尝试对 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 中的代码与这个非常相似,但它不起作用。为什么?

4

0 回答 0