title: Java Multithreaded client/server - java.net.SocketException: Socket closed
body: <p>I have to write a multithreaded client and server using Java's socket api. Both the client and server are multithreaded, so the server can handle multiple connections and the client can test the server's ability to handle connections. </p>
  
  <p>My code is here: <a href="https://github.com/sandyw/Simple-Java-Client-Server" rel="noreferrer">https://github.com/sandyw/Simple-Java-Client-Server</a></p>
  
  <p>I am having a couple, probably related issues. One, occasionally one of the client threads will throw</p>
  
  <pre><code>java.net.SocketException: Socket closed
      at java.net.SocketInputStream.socketRead0(Native Method)
      at java.net.SocketInputStream.read(SocketInputStream.java:129)
      at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
      at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
      at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
      at java.io.InputStreamReader.read(InputStreamReader.java:167)
      at java.io.BufferedReader.fill(BufferedReader.java:136)
      at java.io.BufferedReader.readLine(BufferedReader.java:299)
      at java.io.BufferedReader.readLine(BufferedReader.java:362)
      at ClientThread.run(ClientThread.java:45)
      at java.lang.Thread.run(Thread.java:680)
  </code></pre>
  
  <p>Which from its position means the server is closing its socket before the client is done reading from it. How can I prevent this?</p>
  
  <p>Also, even counting the threads which throw the <code>Socket closed</code> exception, it seems that not all the server threads are sending their output. For example, 23 of the 30 server threads will send their output, but only 22 of the client threads will receive anything. The communications are obviously getting lost somewhere, how do I prevent this? </p>