title: Unexplained SocketException in Java client connecting to localhost
body: <p>I have a Java program running on an iSeries which connects to a server process on the same host. Here's an edited version of the Java client code:</p>
  
  <pre><code>while (true) {         
   try {
    socket = new Socket(myHost, myPort);
   } catch (UnknownHostException ex) {
    // Quit
   } catch (ConnectException ex) {
    // Wait for a while and retry
    continue;
   } catch (IOException ex) {
    // Quit
   }
   break;
  }
  
  // Do stuff with socket...
  </code></pre>
  
  <p>Occasionally, on calling the Socket() constructor, I get a SocketException which falls into the IOException handler which exits the application (this might be a slightly harsh reaction but I don't want to change this until I understand the issue more fully). Here's the stack trace:</p>
  
  <pre><code>java.net.SocketException: A connection with a remote socket was reset by that  
   at java.lang.Throwable.&lt;init&gt;(Throwable.java:195)                             
   at java.lang.Exception.&lt;init&gt;(Exception.java:41)                              
   at java.io.IOException.&lt;init&gt;(IOException.java:40)                            
   at java.net.SocketException.&lt;init&gt;(SocketException.java:29)                
   at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305)            
   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158)              
   at java.net.Socket.connect(Socket.java:488)                                
   at java.net.Socket.connect(Socket.java:438)                                
   at java.net.Socket.&lt;init&gt;(Socket.java:148) 
   at com.foo.AccessObject.&lt;init&gt;(AccessObject.java:36)  
  </code></pre>
  
  <p>I understand that if I am reading from a socket and the other peer closes it, that I will get a SocketException. I also understand that if the connection fails I will get a ConnectionException. What I don't understand is how I can get a SocketException on creating a Socket. I think I can eliminate dodgy network devices as the connection is going to localhost. </p>
  
  <p>I can potentially work around this issue by catching SocketException instead of ConnectionException but I don't want to mask this issue, at least until I understand it more. Does anyone have any ideas about what could be causing the error?</p>