How to check if the remote server is available before flushing buffered output stream in java

31 views Asked by At

I am trying to flush data in the output stream to a remote server. I want to check if the remote server is up and running before I perform BufferedOutputStream.flush(). It is expected that this statement should throw an exception when the remote server is down, but it is observed that during the first flush, there is no exception thrown but throws an exception for all the further flush.

// These are the instance variable that I used to create Socket and BufferedOutputStream.
Socket connection= new Socket();
InetSocketAddress server =
                new InetSocketAddress("server", port);
connection.setSoTimeout(2000);
connection.setKeepAlive(true);
connection.connect(server , 2000);
BufferedOutputStream output = new BufferedOutputStream(connection.getOutputStream());
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());

//I am reusing the same socket
private void send()
{
    output.write("Hello".getBytes());
    output.flush();//Does not throw an exception for the first time when the remote server is down.
}

Is there any way to check the connection before executing the flush? These are the things that I tried.

  • SocketChannel.open() and check the connection with SocketChannel.
  • Socket.isConnected().
  • InetAddress.getByName("your server url").isReachable(2000);
0

There are 0 answers