title: Eliminate Half Strings when receiving from Server socket Buffer in JAVA
body: <p>I have written a simple NIO Server and Inner-Client (Inside the same program)in a single program such that Server receives data from outside and the Inner-Client sends the data received by the server to out side Server. I am running both the processes continuously in two parallel threads using While() loops. Now the problem is, I will be receiving data at a very high speed to the Inside server and everything I receive, I will send them to the outer server using the Inside client. Some times, the retrieval of the data from the Buffer resulting in half the size of the total string. That means I am receiving "HELLO", but the total string is "HELLO SERVER". This is just an example. I will receive very long strings. Similarly, after sending the data to Outer-server through Inner client I will be listening for data and I am receiving the same half-strings.Is there any way I can eliminate these Half-strings and get the full-length string. I have to get the full string without any fail.</p>
  
  <p>I am using while loops for the process. This is making the CPU utilization go high like 50%.  Is there any way I can reduce the CPU utilization without using Thread.sleep method? Because I need to continuously listen to data from the Outer parties. They may send 2-4 strings for one single request.  I tried using Executor service thread for running the processes continuously but it requires some sleep to be included. If I include some sleep I am not able to get the String and if I don't include the sleep my CPU-Utilization is going very high (50-60%). Can anyone help me with these two issues? </p>
  
  <p>Here is my code:</p>
  
  <pre><code>import java.io.IOException;
  import java.net.InetSocketAddress;
  import java.net.Socket;
  import java.net.SocketAddress;
  import java.net.StandardSocketOptions;
  import java.nio.ByteBuffer;
  import java.nio.channels.ServerSocketChannel;
  import java.nio.channels.SocketChannel;
  import java.nio.charset.Charset;
  import java.util.concurrent.BlockingQueue;
  import java.util.concurrent.LinkedBlockingQueue;
  
  public class Main {
      static SocketChannel channel;
      public static void main(String[] args) throws IOException {
  
          System.out.println("Listening for connections on : 8888");  //8888
          ServerSocketChannel serverChannel = ServerSocketChannel.open();
          serverChannel.bind(new InetSocketAddress(8888));
          channel = serverChannel.accept();
          System.out.println("Connected...");
          channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
          channel.configureBlocking(false);
          ReceiveFromOMS receivefromOMS;
          SendToExchange sendExchange;
          receivefromOMS = new ReceiveFromOMS();
          sendExchange = new SendToExchange();
  
          Thread t1 = new Thread(receivefromOMS);
          Thread t2 = new Thread(sendExchange);
          t1.start();
          t2.start();
      }
  }
  
  class ReceiveFromOMS extends Thread{
      public static SocketChannel channel;
      static ByteBuffer buffer =  ByteBuffer.allocate(1024);
      static ServerSocketChannel serverChannel ;
      public static int ReceiveFromOMSPort;
      BlockingQueue&lt;String&gt; fromOMSqueue = new LinkedBlockingQueue&lt;&gt;(30);
  
       @Override
      public void run(){
        while(true){
            try {
                receiveFromOMS();
            } catch (InterruptedException ex) { 
                System.err.println(ex.getMessage());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex1) { }
             }
               }
      }
  
      public void receiveFromOMS() throws InterruptedException{
          try {
              int numRead = -1;
              numRead = channel.read(buffer);
              while(numRead==0){
                  numRead = channel.read(buffer);
              }
              if (numRead == -1) {
                  Socket socket = channel.socket();
                  SocketAddress remoteAddr = socket.getRemoteSocketAddress();
                  System.out.println("Connection closed by client: " + remoteAddr);
                  channel.close();
                  return;
              }
              byte[] data = new byte[numRead];
              System.arraycopy(buffer.array(), 0, data, 0, numRead);
              fromOMSqueue.add(new String(data));
              String msg = fromOMSqueue.poll();
              System.out.println("OutGoing To Exchange&gt;&gt; " + msg);
              SendToExchange.sendToEchange(msg);
              buffer.flip();
              buffer.clear();
  
          } catch (IOException ex) {
              System.err.println(ex.getMessage());
              Thread.sleep(5000);
          }
     }
  }
  
  
  class SendToExchange extends Thread{
      static SocketChannel channel;
      static ByteBuffer bb = ByteBuffer.allocateDirect(1024);
      static Charset charset = Charset.forName("UTF-8");
      public byte[] data;
      public static String message;
  
      @Override
      public void run(){
          try {
             while(true){
             receive();
             Thread.sleep(100);
             }
          } catch (IOException | InterruptedException ex) {
                System.err.println(ex.getMessage());
              try {
                  Thread.sleep(5000);
              } catch (InterruptedException ex1) {}
          } 
      }
  
     public static void sendToEchange(String msg){
          try {
              bb = stringToByteBuffer(msg, charset);
              channel.write(bb);
             } catch (IOException ex) {
              System.err.println(ex.getMessage());
          }
     }
      public void receive() throws IOException {
  
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
  
        int numRead = -1;
              numRead = channel.read(buffer);
              while (numRead == 0) {
              numRead = channel.read(buffer);
               }
  
              if (numRead == -1) {
                  Socket socket = channel.socket();
                  SocketAddress remoteAddr = socket.getRemoteSocketAddress();
                  System.out.println("Connection closed by Exchange: " + remoteAddr);
                  channel.close();
                  return;
              }
              buffer.flip();
              data = new byte[numRead];
              buffer.get(data);
              message = new String(data);
              System.out.println("Incoming from Exchange&gt;&gt; " + message);
              buffer.clear();
  
    }
     public static ByteBuffer stringToByteBuffer(String msg, Charset charset){
          return ByteBuffer.wrap(msg.getBytes(charset));
    }
  }
  </code></pre>