Reputation: 125
I have this little app for android where I connect to my server using sockets. But when I try to send Strings from the Client to the Server it does only send the Strings, when I close the socket after I wrote PrintWriter.println("message") and PrintWriter.flush()...
pw.println("user$" + user.getUserName() + "/" + user.getEmail() + "/" + user.getPassword());
pw.flush();
sock.close(); //Without this it doesn't work!
Server-side I have this code:
String message;
while((message = br.readLine()) != null) {
System.out.println("Message:" + message);
}
I have tried everything, I added '\n' to the message, I used a BufferedWrite and so on, but nothing worked...
EDIT: I don't have to close the Socket entirely, I can just call sock.shutdownOutput()... But this is of course also a problem...
EDIT 2: I'm using a Nexus 7, a real device if that helps.
Okay, this seems to be a general Problem... I've made a really easy example (not android), but it still does not work. It just works if I use localhost, but as soon as I use my IP Address, I have to close the OutputStream in order to send the message... Any ideas?
Upvotes: 2
Views: 1416
Reputation: 24444
Your server reads full lines (reader.readLine()
) which must be terminated by either '\r
', '\n
' or both ("\r\n
"). But your client never writes any of these line termination characters (writer.write("Hello")
only writes the characters Hello
and nothing more).
So when you close the socket on the client, the socket-InputStream
on the server is closed too and causes the readLine()
call to return all the character data as one single line. (The next call to readLine()
will then return null
, as the stream is already closed).
(I think this is exactly what @EJP meant in his/her answer!)
Solution: Either call writer.newLine()
whenever a line is complete, or wrap it into a PrintWriter
instead of a BufferedWriter
. Then you can use one of the many println(...)
methods.
Upvotes: 2
Reputation: 310884
If you've called println() and flush(), readline() will return a line. However your loop won't exit until you close the socket, because that's the only thing that causes readLine() to return a null.
Upvotes: 0