簡體   English   中英

Java socket readLine() 方法異常行為

[英]Java socket readLine() method strange behavior

我在套接字服務器中有以下代碼片段進行測試。

try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    PrintWriter out = new PrintWriter(client.getOutputStream(), true)){

    String input;
    while ((input = in.readLine()) != null) {
        if (input.equalsIgnoreCase("exit")) {
            System.out.println("Received `exit`... closing client " + client.getRemoteSocketAddress());
            break;
        }

        System.out.println("Received: " + input);
        out.println("OK");
    }
} catch(IOException e) {
    e.printStackTrace();
}

當我用空白向它發送一行時,例如Hello World ,它只打印Hello 似乎readLine()方法的行為就像在讀取空白時終止了行。

是字符編碼問題還是什么? 任何幫助將非常感激。

在評論中,您提到了如何發送數據:

Scanner keyboard = new Scanner(System.in);
out.println(keyboard.next());

實際上, Scanner.next()調用分別返回每個單詞,如文檔中所述

Scanner使用分隔符模式將其輸入分解為標記,默認情況下匹配空格

天真地,您可能希望在鍵入空格后立即在服務器上看到Hello 這不會發生,因為輸入 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 默認情況下是行緩沖的,因此在您按 Enter 之前Scanner看不到任何輸入。

要逐行讀取輸入,您不需要Scanner 只需將System.in包裝在BufferedReader中並使用其readLine()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM