title: Create listener for server socket response?
body: <p>I have a server-client pair and I want to create a listener on the client end for new server responses. I am not sure how to do this, right now I can only interact in a direct synchronous way. </p>
  
  <p>Here is the server: </p>
  
  <pre><code>public class TestServer {
  
  public static void main(String[] args) throws Exception {
  
      TestServer myServer = new TestServer(); 
      myServer.run(); 
  
  }
  
  private void run() throws Exception {
  
      ServerSocket mySS = new ServerSocket(4443);     
  
      while(true) {
  
          Socket SS_accept = mySS.accept(); 
  
          BufferedReader myBR = new BufferedReader(new InputStreamReader(SS_accept.getInputStream()));
  
          String temp = myBR.readLine(); 
          System.out.println(temp); 
  
  
          if (temp!=null) {
  
              PrintStream serverPS = new PrintStream(SS_accept.getOutputStream()); 
              serverPS.println("Response received: " + temp); 
  
          }
  
      }
  }
  </code></pre>
  
  <p>}</p>
  
  <p>As you can see, it sends a response when it gets one. However in general I won't be sure when other servers I use send responses, so I would like to create an asynchronous listener (or at least poll the server for a response every half-second or so). </p>
  
  <p>Here is what I'm trying on the client end: </p>
  
  <pre><code>protected static String getServerResponse() throws IOException {
  
      String temp;
      try {
          BufferedReader clientBR = new BufferedReader(new InputStreamReader(mySocket.getInputStream())); 
          temp = clientBR.readLine(); 
      } catch (Exception e) {
          temp = e.toString(); 
      }
  
      return temp; 
  }
  </code></pre>
  
  <p>And just for reference, yes, sending over data from client to server works fine (it System.out's the data correctly). However, when I call the above function to try and retrieve the server response, it just hangs my application, which is an Android application in case that's relevant. </p>
  
  <p>What I want from a function is just the ability to ask the server if it has data for me and get it, and if not, then don't crash my damn app. </p>