質問

I am building a client/server application and I am trying to send a String to the client from a server thread using a PrintWriter. I construct my PrintWriter like this:

// Instantiate a PrintWriterwith a correctly implemented 
// client socket parameter, and autoflush set to true
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

Assume, further, that the client is reading from the input stream with a BufferedReader, that is instantiated as such:

BufferedReader in = new BufferedReader(new InputStreamReader(client.server.getInputStream()));

and the client gets messages from the server with:

String serverMessage = in.readLine();

As you can see, I've set autoflushing to true. Let's say, now, that I want to send a simple message to a client. If I execute the statement:

out.println("Message to client");

Then the message is successfully sent. However, if I execute the statement:

out.print("Message to client");

then the message is not sent. Also:

out.print("Message to client");
out.flush();

does not work either.

This is a problem because I need to send a message to a client in a terminal and have them be able to respond on the same line. How do I send a message, using a PrintWriter, so that it gets flushed/sent to the client, but it does not send a newline character?

役に立ちましたか?

解決

In your case it seems like you are using BufferedReader#readLine() which will read characters until a newline character or the end of stream is reached, blocking in the meantime. As such, you'll need your server to write that new line character.

An alternative is to read bytes directly instead of relying on BufferedReader#readLine().

why doesn't using a carriage return work?

The newline character is system-dependent. On Windows it is \r\n. On linux it is \n. You can get that with

System.getProperty("line.separator")

but you will need to get the server's.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top