title: How to make fast data reading using socket in Java?
body: <p>I'm using SocketChannel for single connection like this:  </p>
  
  <pre><code>int sampleBufferSize = 50;
  StringBuilder data = new StringBuilder();
  ByteBuffer bf = ByteBuffer.allocate(sampleBufferSize);
  SocketChannel sc = new SocketChannel();
  while(true)
      if(sc.read(bf) &gt; 0){
          bf.flip();
          while(bf.hasRemaining())
              data.append((char) bf.get());
          bf.clear();
      }else{
          fireDataReceived(data.toString());
          data.delete(0, data.length());
      }
  </code></pre>
  
  <p>This code is not very efficient, but it reads HTTP POST request 130 KB from the same PC in 0.05 seconds. Now I'm trying to write a class with similar functionality but using Socket. Here is the code:  </p>
  
  <pre><code>private static final int TIMEOUT_MILLIS = 50;
  private boolean reading = false;
  private long readBeginTime = 0;
  private StringBuilder buffer = new StringBuilder();
  private Thread thread = new Thread(){
      public void run(){
          while(!isInterrupted()){
              try {
                  int b = getInputStream().read();
                  if(b == -1){
                      if(reading)
                          fireDataReceived();
                      close();
                  }else{
                      if(!reading){
                          reading = true;
                          readBeginTime = System.currentTimeMillis();
                          setSoTimeout(TIMEOUT_MILLIS);
                      }
                      buffer.append((char) b);
                  }
              } catch (SocketTimeoutException e){
                  fireDataReceived();
              } catch (IOException e) {
                  e.printStackTrace();
                  if(reading)
                      fireDataReceived();
                  close();
              }
          }
      }
  };
  private void fireDataReceived(){
      BufferedSocketEvent e = new BufferedSocketEvent(this, System.currentTimeMillis() - readBeginTime, buffer.toString());
      buffer.setLength(0);
      reading = false;
      try {
          setSoTimeout(0);
      } catch (SocketException e1) {
          e1.printStackTrace();
      }
      for(BufferedSocketListener listener: listeners)
          listener.dataReceived(e);
  }
  </code></pre>
  
  <p>And the problem is that it takes 0.4 seconds for the same request and I have no idea why does it take so long. Please, explain what is wrong with my code.</p>