Salman Younas
Salman Younas

Reputation: 350

Java Socket Programming: Detect whether client and server are connected

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();
}

Upvotes: 0

Views: 1374

Answers (1)

user207421
user207421

Reputation: 311031

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.

Upvotes: 1

Related Questions