title: Java server socket reading
body: <p>I have a very peculiar problem and my last resort was asking this on StackOverflow, so please be open minded!</p>
  
  <p>Here are two programs:</p>
  
  <p>A. Client: A java client running on an Android phone.
  B. Server: A java server running on a Computer.</p>
  
  <p>Here is what the two programs do:</p>
  
  <p>Client sends server coordinates (in string format) every 2 milliseconds (very fast), and the server must read all those coordinates that the client sends it. In order to achieve this (given that the server is located at 10.0.0.1 and is listening on port 54321), the server must have a socket via which it reads all the incoming info. And yes, it does receive all of the information, BUT, there is a catch!</p>
  
  <p>Now that you have the background behind the story, here is the problem:</p>
  
  <p>The client connects to the server and as soon as that happens,it starts sending coordinates (in string format) at an extremely fast rate. The server does get all the messages, but it does not stop reading unless the client has disconnected. What i need is for the server to read every single message individually as they received!</p>
  
  <p>Here is the code i used to read from the socket (this is for the server, and it is on its own thread):</p>
  
  <pre><code>    while(true) {
          try {
              BufferedReader socketReader = 
              new BufferedReader(new InputStreamReader(socket.getInputStream()));
              String str = socketReader.readLine();
              System.out.println("New Message: " + str);
              socketReader.close();
          } catch (IOException e) {
              //Client disconnected
              System.out.println("Client disconnected.");
              break;
          }
      }
  </code></pre>
  
  <p>This is the output i am getting from the client (where x and y are numbers):</p>
  
  <pre><code> New Message: x,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,yx,y...and so on
  </code></pre>
  
  <p>And that text only shows up AFTER the client has disconnected. I want it to show up AS THE MESSAGES come in.</p>
  
  <p>Just to clarify, this is the desired output:</p>
  
  <pre><code> New Message: x,y
   New Message: x,y
   New Message: x,y
   New Message: x,y
   ... and so on
  </code></pre>
  
  <p>In case this is of any use, here is the method of writing to the socket (this code is from the client)</p>
  
  <pre><code>PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
  while(running) {
      writer = new PrintWriter(socket.getOutputStream(), true);
      writer.write(x+","+y);
      writer.flush();
  }
  </code></pre>
  
  <p>So all in all, what i need is for my server to read the messages as they come in instead of reading them all at the same time after the client disconnects. P.S in C# i have also written a server and that one reads the info as it comes in, but in Java this isnt working out!</p>