开发者

Java Server reply is not printed as expected

I am building a simple client-server program , I have in main :

FTPClient ftp = new FTPClient("www.kernel.org");
ftp.getReply();
ftp.sendCommand("USER " + "anonymous");
ftp.getReply();
ftp.sendCommand("PASS " + "anonymous");
ftp.getReply();
String com="";
while (!com.equalsIgnoreCase("quit")){
    System.out.println("Enter your Commands . or Enter quit");
    BufferedReader Keyboard = new BufferedReader(new InputStreamReader(System.in));
    com = Keyboard.readLine();
    ftp.sendCommand((com));
    ftp.getReply();
    System.out.println("=开发者_如何学运维==============");
}
ftp.close();

the problem is in the getReply() function, this function is :

public void getReply() throws IOException {
    String line="";
    while (br.ready())
    {
        line = br.readline();
        System.out.println(line);
        System.out.flush();
    }
}

br is a BufferedReader.

Now all the problem is that when the program starts it doesn't show the welcome message from the Server until I press Enter or any command, when I Debug the program Step by Step every thing is working perfectly.So is the problem in the readline and I should use something else or what?


The problem is likely that the end of the server response does not contain a newline character. The BufferedReader's readLine method will block until a line of data is received, where "a line" consists of some characters followed by a newline character (or the end of the stream). Consequently, the readLine call will not return if no newline is received.

In this situation then, the BufferedReader isn't doing you any good. You'd be better off using the underlying Reader yourself, reading into an array and emitting the output as soon as it comes in, such as the following:

final char[] buffer = new char[256]; // or whatever size you want
int nRead;
while ((nRead = reader.read(buffer)) != -1)
{
    System.out.println(new String(buffer, 0, nRead));
    System.out.flush();
}

The condition in the while loop there might look confusing if you're not used to it before, but it combines the read operation (which reads into the buffer) with the check that the end of the stream has not been reached. Likewise, the construction of the String within the while loop takes into account the fact that the buffer may not have been filled entirely, so only as many characters as were supplied are used.

Note that this particular snippet keeps looping until the stream is empty; you may wish to add another exit condition in your particular case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜