title: Synchronizend Socket messages in Java
body: <p>I'm new to <code>Sockets</code> and I've written a <strong>TCP</strong> client following tutorials, that's basically like this:</p>
  
  <pre><code>public boolean send(String message) {
  
      if(out != null &amp;&amp; !out.checkError()) {
          out.println(message);
          out.flush();
          return true;
      } else {
          return false;
      }
  }
  
  @Override
  public void run() {
      socket = new Socket(SERVER_IP, SERVER_PORT);
  
      out = new PrintWriter(
              new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
  
      in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  
      while (mRun &amp;&amp; (response = in.readLine()) != null &amp;&amp; socket.isConnected()) {
          Message message = Message.obtain();
  
          if (message != null) {
              message.obj = response;
              mHandler.sendMessage(message);
          }
      }
  }
  </code></pre>
  
  <p>So from the main <code>Thread</code> I send messages to the server using <code>TCPClient#send(String)</code>, but it will respond <strong>asynchronously</strong> using <code>mHandler.sendMessage(Message)</code>.</p>
  
  <p>I was wondering, if in order to send messages synchronously (waiting for the server response before sending the next one) the architecture of my <code>TCPClient</code> should be different (I'm also new to <code>InputStream</code> and <code>OutputStream</code> so that's why I'm confused)  or if this client is good to go, and I have to implement the synchronization logic by myself (using <strong>callbacks</strong> and <strong>flags</strong>).</p>
  
  <p><em>PS: I'm asking this question because all socket tutorials have the same skeleton as the one I posted, but also, neither of them should <strong>wait for the server response</strong> in order to write again, as a requirement.</em></p>