I am working on a Java client which has to send a heartbeat message periodically. I am using java.net.Socket for the work. My issue is even the server is stopped client goes on sending the messages without giving any exception.
I read various stackoverflow questions on this, but couldn't find the answer for my implementation. I read that only way to find the server is up is to try sending a message. But here I don't see a way to do this.
Here's how my class looks like.
public void process() {
sendMessage(HEART_BEAT);
}
public void start(String serverAddress, int port) throws IOException {
this.serverAddress = serverAddress;
this.port = port;
if (isConnected) {
LOGGER.info("Already connected");
return;
}
socket = new Socket(serverAddress, port);
out = new PrintWriter(socket.getOutputStream(), true);
}
private void sendMessage(String message) {
out.print(message + END_OF_MESSAGE);
out.println();
}
Here's how my main method looks like,
public static void main(String args[]) {
Client client=new Client();
client.start("127.0.0.1", 900);
while(true) {
client.process();
Thread.sleep(2000);
}
}
How to implement a way to identify when the server has stopped?