簡體   English   中英

Java PrintStream 立即使用 Scanner 和循環輸出到 outputStream

[英]Java PrintStream immediately to outputStream with Scanner and loop

我正在嘗試循環掃描儀讀取一行,立即通過 printStream 將其發送到應該打印它的客戶端,然后等待來自服務器的另一行。

我的客戶端在打印第一條消息后一直卡住,之后才返回 null。 我想我不應該在 Server.java 中調用 printStream.close(),但是直到我關閉它才會傳輸消息。 printSteam.flush 似乎沒有做任何事情。

相關代碼:

服務器端.java

       ServerSocket serverSocket = new ServerSocket(1234);
       Socket connectionSocket = serverSocket.accept();
       OutputStream outputStream = connectionSocket.getOutputStream();

       Scanner sc = new Scanner(System.in);

        while(true) {

            System.out.print("Pass me a message: ");
            String input = sc.nextLine();

            final PrintStream printStream = new PrintStream(outputStream);
            printStream.print(input);
            printStream.flush();
            printStream.close();
        }

客戶端.java

        Socket connectionSocket = new Socket("localhost", 1234);
        InputStream inputStream = connectionSocket.getInputStream();

        String result = "";
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(inputStream));

        while (true) {

            result = inFromServer.readLine();
            System.out.println("Message: "+result);
        }

感謝您的幫助!

關閉 PrintStream 后,它就完成了。 如果它后面有一個套接字連接,它將關閉該連接。 相反,在循環之外創建 PrintStream 並且不要關閉它

    final PrintStream printStream = new PrintStream(outputStream);
    while(true) {

        System.out.print("Pass me a message: ");
        String input = sc.nextLine();

        printStream.print(input);
        printStream.flush();
    }

暫無
暫無

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

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