1

I have written a simple network engine for client-server communication. It works perfectly on Windows, server knows when the client disconnected etc. (readLine() throws exception). I tried to port the engine to Android and sending and receiving data works, but for some reason server does not detect when the socket is closed (readLine() is still blocked and does not throw any exception). I even tried disconnecting the Android device from internet and it still did not detect closed socket. I thought of a workaround by implementing timeout, when the client does not send something for a long time, server will think that he is disconnected, but that's probably not a good permanent solution.

Code is surrounded by try-catch exception:

String userInput;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while ((userInput = stdIn.readLine()) != null) {
    //do something
}
Ladas125
  • 265
  • 3
  • 14
  • Does the socket get orderly closed or shut down by the peer? – alk Sep 13 '15 at 12:26
  • @alk Not sure what you mean by that, but the server needs to know when the client disconnected even if client did not force close the socket by socket.close(), for example when the app is terminated by force, it can't call socket.close(). – Ladas125 Sep 13 '15 at 12:40
  • 4
    There are 100s of questions on stackoverflow which all ask about the same what you ask. One of these is [Why is it impossible, without attempting I/O, to detect that TCP socket was gracefully closed by peer?](http://stackoverflow.com/questions/155243/why-is-it-impossible-without-attempting-i-o-to-detect-that-tcp-socket-was-grac) – Steffen Ullrich Sep 13 '15 at 13:45

1 Answers1

0

I found a solution! Socket on Android instead of throwing exception causes readLine() to be null, but server code did nothing in case that the while stops when readLine() is null. So I fixed it by adding some code after the while statement.

Ladas125
  • 265
  • 3
  • 14