简体   繁体   中英

Java PrintStream immediately to outputStream with Scanner and loop

I'm trying to loop a Scanner to read a line, send it immediately via a printStream to a client who should print it and then wait for another line from the Server.

My client keeps getting stuck after printing the first message and only returns null afterwards. I guess I should not call printStream.close() in the Server.java, but the message won't be transmitted until I close it. printSteam.flush doesn't seem to do anything.

The relevant code:

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);
        }

Thank you for your help!

Once you close the PrintStream it's done. If there's a socket connection behind it, it will close that connection. Instead, create the PrintStream outside of your loop and don't close it

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM