Importance of the new line “\\n” in Java networkin

2020-02-07 11:05发布

问题:

Well, I need a clarify of what is the importance of the "\n" new line in the String variable here

import java.net.*;
import java.io.*;

public class Whois{
    public static void main(String[] args){
        try{
            Socket soc = new Socket("whois.internic.net",43);
            InputStream in = soc.getInputStream();
            OutputStream out = soc.getOutputStream();
            String url = "http://www.infiniteskills.com\n";
            byte[] buffer = url.getBytes();
            out.write(buffer);
            int c;
            while((c = in.read()) != -1){
                    System.out.print((char)c);  
            }
            in.close();
            out.close();
        }catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
}

Note :- without the \n the program doesn't work correctly and no output.

回答1:

The newline has no importance in Java networking.

However it does have importance in many protocols, many of which are based on the 'Telnet Terminal' convention of \r\n as the line terminator. This certainly includes SMTP, FTP, HTTP, and Telnet itself.

It also has importance for the BufferedReader.readLine() method. You will find hundreds of questions here about readLine() blocking forever, to which the answer is 'you are reading lines but you are not writing lines', i.e. just sending a string with no line terminator. This does not constitute a complete line, so readLine() doesn't return it.



回答2:

TCP port 43 is the WHOIS protocol explained here on Wikipedia: Whois

If you see the article is says: Send a single "command line", ending with CRLF.
That's why you need the newline in your code.