[英]Why can't I run this tcp client socket code without \n?
我正在嘗試此代碼。 它工作正常,但是如果我刪除String str
中的\\n
,它不起作用我的意思是它可以在沒有\\n
情況下進行編譯,但它沒有給我輸出。
public class Test {
// Use try-with-resources to close a socket.
public static void main(String args[]) throws Exception {
int c;
// Create a socket connected to internic.net, port 43. Manage this
// socket with a try-with-resources block.
try (Socket s = new Socket("whois.internic.net", 43)) {
// Obtain input and output streams.
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// Construct a request string.
String str = (args.length == 0 ? "MHProfessional.com" : args[0]) + "\n"; // <- herer
// Convert to bytes.
byte buf[] = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
}
// The socket is now closed.
}
}
您正在與之交談的服務器讀取數據直到行尾 (\\n) 字符——這就是它的工作方式,但這遠非異常。 也有可能接受其他行尾序列。
服務器必須通過某種方式知道客戶端已完成發送數據。 它可能會知道客戶端是否關閉了它的連接,但到那時響應客戶端已經太晚了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.