Java PrintStream立即使用Scanner和loop输出outputStream

时间:2017-02-14 20:27:45

标签: java java.util.scanner bufferedreader outputstream

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

我的客户端在打印第一条消息后一直卡住,之后只返回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);
        }

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

关闭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();
    }