Java PrintStream 立即到 outputStream with Scanner 并循环

Java PrintStream immediately to outputStream with Scanner and loop

我正在尝试循环扫描仪以读取一行,立即通过 printStream 将其发送到应打印它的客户端,然后等待来自服务器的另一行。

我的客户端在打印第一条消息后一直卡住,之后只有 returns null。我想我不应该在 Server.java 中调用 printStream.close(),但在我关闭它之前不会传输消息。 printSteam.flush 好像什么都没做。

相关代码:

Server.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();
        }

Client.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();
    }