0

I'm working on an android app. The app is acting as a client. It is sending some data to a server continuously (lets say after every half second). The server is running on my PC. How can I detect from my app that the server has closed so that I can notify the user of this? Below is my code to send data from client to server:

Socket socket = null;
PrintWriter out = null;
try {
    socket = new Socket(ip, PORT);
    out = new PrintWriter(socket.getOutputStream(), true);
    out.println(myMessage);
}
catch (IOException e) {
    e.printStackTrace();
}
Salman Younas
  • 340
  • 1
  • 7
  • 20
  • Is there anything after this code that continues to use the `socket`? – zapl May 25 '16 at 17:23
  • 1
    Check [this post](http://stackoverflow.com/questions/1390024/how-do-i-check-if-a-socket-is-currently-connected-). I think it answers your question. This [link](http://stackoverflow.com/questions/865987/do-i-need-to-heartbeat-to-keep-a-tcp-connection-open) expounds. – caburse May 25 '16 at 17:25
  • Yes, I keep on sending messages using out.println(). I do this in a different thread which keeps on sending messages after every half second. – Salman Younas May 25 '16 at 17:27
  • @caburse I already studied these 2 links but I'm unable to implement it in my scenario. – Salman Younas May 25 '16 at 17:29
  • You get an exception when the connection isn't there anymore. But it's not guaranteed that the connection is still alive just because you didn't get one yet. For that you have to implement some sort of heartbeat (e.g. let your server send `"ping"` every 10 seconds and set a read timeout on the socket + simply void the data you get) – zapl May 25 '16 at 17:34

1 Answers1

1

PrintWriter swallows exceptions. Don't use it in networking code. Use BufferedWriter. You will get an exception when sending if the server has disconnected ... but not immediately, due to TCP buffering.

user207421
  • 305,947
  • 44
  • 307
  • 483