Reputation: 11
I am writing an application on Android, and I want it to be able to know when the server (which I have written in C) dies or is shutdown. I am trying to implement this by having the server send a message to the client (the Android app) at a specified interval. If this message doesn't come, then the client knows that it is no longer connected to the server. They communicate using TCP sockets.
My problem is that the Android app cannot seem to read what the server writes. When it gets to the first part of the code where it tries to read from the server socket, it just hangs. In the Android app I am using a BufferedReader to read from the socket tmpstr = inFromServer.readLine();
where tmpstr is a string and inFromServer is the BufferedReader, and the C server is just using write write(newsockfd,"I got your message",18);
.
I also tried using an alternative java server to see if my basic program logic was wrong. The test server used a PrintWriter, and it worked perfectly with the Android client.
What am I missing here? Is there a difference in the way Java and C buffer (or don't buffer) their data? If I need to give any additional information, please let me know.
Edit: I also have no trouble getting the C server to read data sent from the client. I only have trouble with getting the client to read data that is sent from the server.
Edit: The problem was fixed by adding a newline character (\n
) to what the server sends to the client.
Upvotes: 1
Views: 1233
Reputation: 1977
If I recall correctly, readLine() is not going to return the result until it has read a full line. It is going to block until then. You are not sending a full line from the C program.
Not only are you not sending a full line (\n terminated), but you also aren't even sending your entire C string since you're not sending the null terminator (Your C string actually contains 19 characters, not 18, if you include the null terminator). I don't recall what type of string format Java uses, if it's null terminated or not, but that part probably doesn't matter since it's looking for a \n, not a \0.
Try sending "I got your message\n" from the C server and let us know what happens then.
Oops, I just realized that the question had already been answered in the comments to it. Oh well. People really should post answers as answers.
Upvotes: 2