Reusing socket and detecting when it needs to be re-established
<p>I'm currently writing client software for android that will repeatedly send request to a server. </p>

<p>Since I figured it would be a waste to keep reconnecting the socket everytime a request is made I tried developing a method in which the socket is used as long as it's active and when it's dead, one attempt will be be done to re-establish contact. </p>

<p>This is my current solution:</p>

<pre><code>class Foo
{
  private Socket socket=null;
    private OutputStream outStream=null;
    private InputStream inStream=null;




    public void someRequest() throws UnknownHostException, IOException
    {
      setupConnection();

      // Do stuff with outStream and inStream here


    }

    private void setupConnection() throws UnknownHostException, IOException
    {

        try
        {
            if(socket!=null &amp;&amp; socket.isConnected() &amp;&amp; !socket.isClosed()) return;


            if(outStream!=null) outStream.close();
            if(inStream!=null) inStream.close();

            socket = new Socket(SERVER_NAME,SERVER_PORT);
            outStream = socket.getOutputStream();
            inStream = socket.getInputStream();
        }
        catch(IOException e)
        {
            socket = null;
            throw e;
        }


    }


}  
</code></pre>

<p>The idea is that all ioexceptions will be caught by the external code calling the someRequest method, however apparently this means that there is no way for my Foo class to know that the socket needs to reconnected! </p>

<p>The only solution I can come up with is catching the exception inside someRequest, signal that the socket is dead and rethrowing the exception, however since I have loads of someRequest type of methods this doesn't seem like a clean solution.</p>

<p>Thanks. </p>
