I have a made a socket connection between client and server. Everything is working good if i introduce the first comand on client, receiving the message i want from the server.
#server
public PrintWriter out;
out.println(res);
#client
public BufferedReader in = null;
String line;
line = in.readLine();
At the second time i run it won't show the message i send from server cause it will read \n so it will be an empty string. If i change this:
#server
out.println("\n"+res);
The first time i run now it will jump a line, printing just the \n. And the second time i run it will show the right message.
If i change now to:
out.println("\n\n"+res);
It will just show when i introduce something to send to the server and receive back after the 3rd time (the first 2 times it prints \n).
Don't know what to do to show always the message i send from the server. Any advice?
Related
I am working on a client/server project for class. I have the server set up so that it is listening for inputs and will relay appropriate message/messages back to the client. For example, client sends input "help" to the server, the server will respond with 5 lines of strings back to the client's console. This is done with the code:
while (true) {
System.out.print('>');
inputLine = bufferedReader.readLine();
toServer.write(inputLine + '\n');
toServer.flush();
while ((serverInput = fromServer.readLine()) != null) {
System.out.println(serverInput);
}
So I believe the problem with this is that it is indefinitely waiting for serverInputs at the end. I would like it to go back to reading inputs from the console after all the appropriate messages have been received. Any help is greatly appreciated. Thank you
I have a classic Java client/server app, where client and server exchange messages by a TCP connection.
When one elemement, let's call it Receiver (no matter if client or server), has to receive a message, it listens and waits for a message coming from the other element, let's call it Sender.
The receiver implements it by the following code:
BufferedReader myBufferedReader = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
receivedMessageCompleto = myBufferedReader.readLine();
The sender, after some time, will send a text message implementing the following code:
String messageCompleto = "whatever text";
String packetSend = messageCompleto + '\n' ;
DataOutputStream myDataOutputStream = new DataOutputStream(mySocket.getOutputStream());
myDataOutputStream.writeBytes(packetSend );
The probelm is:
in some cases "myBufferedReader.readLine()" get null value, but I'm quite sure that the sender didn't send a message NULL.
The question is: why?
According to my understanding the Receiver should remain blocked until it receives something (let's consider that timeout is set to infinite), then "myBufferedReader.readLine()" should return a value only when something arrives. The point is that I'm sure that the sender didn't send a null message.
Any idea???
Thank you very much in advance
Fausto
public String readLine()
throws IOException
Reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage return
followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached
Basically you get null if the underlying stream hits EOF.
As it says in the documentation for the readLine method:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been
reached
So, in your case, end-of-stream has been reached. Probably, the remote end of the socket was closed.
I started to learn about server-client application and I used this Java code example for client and server:
http://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java
http://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java
I ran both applications on two instances of Eclipse.
The code remain the same, except for the change:
//out.println(inputLine);
System.out.println(inputLine);
In the server side.
And to the printings "Hello", "Bye" in the beginning and end of the main() in the server-side. And of course, I set the IP used by the Client to the IP of my computer (used ipconfig - not unique IP)
From what I understand, everything the client sends should appear on the server standard output until the client types "Cntrl C" (unless I understand wrong).
here is the input I wrote in the client side:
boooooooooo
baaaaaa
paaaaaaa
And this is what I get in the Server-side:
Hello
boooooooooo
Something in here is unexpected to me-
the server seem to run in the main(),
but from some reason after the first printing it stops.
I tried o set breakpoints inside the Client side code on the while-line
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
but the program flow encountered the while only twice an then didn't reach there anymore.
when it did enter in, userInput was not evaluated, I suspect because readline() returned null. But why should it? if EOF character wasn't inserted to the standard input in the Client side.
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.
So, I have a simple socket server and a socket. I run the socket server, successfully. The client socket connects and sends a string - this works. I want the server to write back different information based on this string. I can check what the string is and get an OutputStream to the client, but whenever I write to it and flush, the InputStream client-side is NEVER in a ready state, and will never get a message back... I just don't see what I'm doing wrong.
All the code is at http://pastebin.com/u/omegazero
NetworkAgent.java is the client, SimbadAgent.java is the server, and UserAgent.java is the actual implementation of said server (the server is abstract for other reasons).
Compile everything, then run UserAgent followed by NetworkAgent and you will see what happens.
Executed your code (after commenting the reference to StringQueue in SimbadAgent) and I got the following output.
wrote get_cmd
Input shutdown? false
iS()iI()iM()iB()iA()iD()i ()iB()iO()iO()iY()iA()NETWORKAGENT: Response to "get_cmd": "SIMBAD BOOYA"