title: Java sockets losing data: BufferedReader
body: <p>I'm having the following problem in java: I am developing and app using <code>java.net.Socket</code>. It looks like that: There is a server with a thread which accepts and adds new client, and another thread which reads data from sockets and does "something" with it. Next to it there are clients. Client has data reader thread as well as a separate thread. I send the data as simple as:</p>
  
  <pre><code>socket.getOutputStream().write((content+"\n").getBytes());
  </code></pre>
  
  <p>on the client side and read it on the server like:</p>
  
  <pre><code>try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String received;
      while(true) {
          try {
              reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
              received = reader.readLine();
              if(received == null) {
                  break;
              }
              System.out.println("SERVER " + received);
              increaseReceivedCounter(1);
          } catch(SocketException e) {
              break;
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  } catch (IOException e) {
      e.printStackTrace();
  } finally {
      System.out.println("SERVER RECEIVED "+ getReceivedCounter() + " MESSAGES!");
  }
  </code></pre>
  
  <p>Now I just set the client to send some amount of messages like this:</p>
  
  <pre><code>try {
      int n = 1000;
      System.out.println("sending "+ n +" messages to " + client);
      for(int i=0 ; i&lt;n ; ++i) {
          socket.getOutputStream().write((content+"\n").getBytes());
      }
      System.out.println("done sending " + n + " messages");
  } catch (IOException e) {
      e.printStackTrace();
  }
  </code></pre>
  
  <p>The problem is that not all of the messages are transferred to a server. I have been looking for some solution for this but didn't manage to achieve 100% reliability. Is it even possible? I also tried with <code>read</code> instead of <code>readLine</code> but the result is the same: sometimes even 90% data loss. I think while server is working on the received data it ignores incoming packets and they're just lost.</p>
  
  <h2>Edit</h2>
  
  <p><code>Socket</code>s initializations:</p>
  
  <pre><code>serverSocket = new ServerSocket(Server.PORT);//PORT = 9876, whatever
  </code></pre>
  
  <p>for the data reader on server side:</p>
  
  <pre><code>socket = serverSocket.accept();
  </code></pre>
  
  <p>on the client:</p>
  
  <pre><code>socket = new Socket("127.0.0.1", Server.PORT)
  </code></pre>