title: how make multithread communication between server java and more android clients
body: <p>I have met headwind with the development of a communication between a Java server and Android clients.</p>
  
  <p>Any suggestions? My communication single thread code is as below.</p>
  
  <p>TCP SERVER.java:</p>
  
  <pre><code> //public static final int SERVERPORT = 110;
  
      public static final int SERVERPORT = 4444;
      //public static final int SERVERPORT =  80;
  
      private boolean running = false;
      private PrintWriter mOut;
      private OnMessageReceived messageListener;
  
      public static void main(String[] args) {
  
          //opens the window where the messages will be received and sent
          ServerBoard frame = new ServerBoard();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setVisible(true);
  
      }
  
      /**
       * Constructor of the class
       *
       * @param messageListener listens for the messages
       */
      public TCPServer(OnMessageReceived messageListener) {
          this.messageListener = messageListener;
      }
  
      /**
       * Method to send the messages from server to client
       *
       * @param message the message sent by the server
       */
      public void sendMessage(String message) {
          if (mOut != null &amp;&amp; !mOut.checkError()) {
              mOut.println(message);
              mOut.flush();
          }
      }
  
      @Override
      public void run() {
          super.run();
  
          running = true;
  
          try {
              System.out.println("S: Connecting...");
  
              //create a server socket. A server socket waits for requests to come in over the network.
              ServerSocket serverSocket = new ServerSocket(SERVERPORT);
  
              //create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
              Socket client = serverSocket.accept();
              System.out.println("S: Receiving...");
  
              try {
  
                  //sends the message to the client
                  mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
  
                  //read the message received from client
                  BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
  
                  //in this while we wait to receive messages from client (it's an infinite loop)
                  //this while it's like a listener for messages
                  while (running) {
                      String message = in.readLine();
  
                      if (message != null &amp;&amp; messageListener != null) {
                          //call the method messageReceived from ServerBoard class
                          messageListener.messageReceived(message);
  
                          //String gongFile = "/Users/marco/Downloads/JavaSoundDemo/audio/ok.wav";
  //                        String gongFile = "src\\tcpserver\\ok.wav";
  //
  //                       InputStream inn = null;
  ////
  //                        AudioStream audioStream = null;
  ////                  
  //                       // inn=new FileInputStream(new File("/Users/marco/NetBeansProjects/TCPServer/src/tcpserver/ok.wav"));
  //                          inn=new FileInputStream(new File("http://www.mircmania.it/suoni/africa.wav"));
  ////
  //                        audioStream=new AudioStream(inn);
  //                        AudioPlayer.player.start(audioStream);
                             // String song = "http://www.mircmania.it/suoni/africa.wav";
  
                           String song = "http://www.mircmania.it/suoni/squillo7.wav";
          //Player mp3player = null;
         // BufferedInputStream inn = null;
          InputStream inn = null;
          AudioStream audioStream = null;
          try {
            inn = new BufferedInputStream(new URL(song).openStream());
            audioStream=new AudioStream(inn);
            AudioPlayer.player.start(audioStream);
           // mp3player = new Player(inn);
           // mp3player.play();
          } catch (MalformedURLException ex) {
          } catch (IOException e) {
          } catch (NullPointerException ex) {
          }
                      }
                  }
  
              } catch (Exception e) {
                  System.out.println("S: Error");
                  e.printStackTrace();
              } finally {
                  client.close();
                  System.out.println("S: Done.");
              }
  
          } catch (Exception e) {
              System.out.println("S: Error");
              e.printStackTrace();
          }
  
      }
  
  
  
      //Declare the interface. The method messageReceived(String message) will must be implemented in the ServerBoard
      //class at on startServer button click
      public interface OnMessageReceived {
  
          public void messageReceived(String message);
      }
  
  }
  </code></pre>
  
  <p>TCP CLIENT.java:</p>
  
  <pre><code>public class TCPClient {
  
      private String serverMessage;
     /* public static final String SERVERIP = "31.220.16.19"; //your computer IP address
      public static final int SERVERPORT = 110;
  */
      public static final String SERVERIP = "192.168.1.38"; //your computer IP address
      public static final int SERVERPORT = 4444;
  /*public static final String SERVERIP = "87.7.183.222"; //your computer IP address
      public static final int SERVERPORT =  4444;*/
      private OnMessageReceived mMessageListener = null;
      private boolean mRun = false;
      PrintWriter out;
      BufferedReader in;
  
      /**
       *  Constructor of the class. OnMessagedReceived listens for the messages received from server
       */
      public TCPClient(OnMessageReceived listener) {
          mMessageListener = listener;
      }
  
      /**
       * Sends the message entered by client to the server
       * @param message text entered by client
       */
      public void sendMessage(String message){
          if (out != null &amp;&amp; !out.checkError()) {
              out.println(message);
              out.flush();
          }
      }
  
      public void stopClient(){
          mRun = false;
      }
  
      public void run() {
  
          mRun = true;
  
          try {
              //here you must put your computer's IP address.
              InetAddress serverAddr = InetAddress.getByName(SERVERIP);
              //InetAddress serverAddr = InetAddress.getLocalHost();
              //System.out.println(serverAddr.toString());
  
              Log.e("TCP Client", "C: Connecting...");
  
              //create a socket to make the connection with the server
              Socket socket = new Socket(serverAddr, SERVERPORT);
  
              try {
  
                  //send the message to the server
                  out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
  
                  Log.e("TCP Client", "C: Sent.");
  
                  Log.e("TCP Client", "C: Done.");
  
                  //receive the message which the server sends back
                  in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  
                  //in this while the client listens for the messages sent by the server
                  while (mRun) {
                      serverMessage = in.readLine();
  
                      if (serverMessage != null &amp;&amp; mMessageListener != null) {
                          //call the method messageReceived from MyActivity class
                          mMessageListener.messageReceived(serverMessage);
                      }
                      serverMessage = null;
  
                  }
  
                  Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
  
              } catch (Exception e) {
  
                  Log.e("TCP", "S: Error", e);
  
              } finally {
                  //the socket must be closed. It is not possible to reconnect to this socket
                  // after it is closed, which means a new socket instance has to be created.
                  socket.close();
              }
  
          } catch (Exception e) {
  
              Log.e("TCP", "C: Error", e);
  
          }
  
      }
  
      //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
      //class at on asynckTask doInBackground
      public interface OnMessageReceived {
          public void messageReceived(String message);
      }
  }
  </code></pre>
  
  <p>MAIN ACTIVITY.java:</p>
  
  <pre><code>public class MainActivity extends Activity
  {
      private ListView mList;
      private ArrayList&lt;String&gt; arrayList;
      private MyCustomAdapter mAdapter;
      private TCPClient mTcpClient;
  
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
  
          arrayList = new ArrayList&lt;String&gt;();
  
          final EditText editText = (EditText) findViewById(R.id.editText);
          Button send = (Button)findViewById(R.id.send_button);
  
          //relate the listView from java to the one created in xml
          mList = (ListView)findViewById(R.id.list);
          mAdapter = new MyCustomAdapter(this, arrayList);
          mList.setAdapter(mAdapter);
  
          // connect to the server
          new connectTask().execute("");
  
          send.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
  
                  String message = editText.getText().toString();
  
                  //add the text in the arrayList
                  arrayList.add("c: " + message);
  
                  //sends the message to the server
                  if (mTcpClient != null) {
                      mTcpClient.sendMessage(message);
                  }
  
                  //refresh the list
                  mAdapter.notifyDataSetChanged();
                  editText.setText("");
              }
          });
  
      }
  
      public class connectTask extends AsyncTask&lt;String,String,TCPClient&gt; {
  
          @Override
          protected TCPClient doInBackground(String... message) {
  
              //we create a TCPClient object and
              mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                  @Override
                  //here the messageReceived method is implemented
                  public void messageReceived(String message) {
                      //this method calls the onProgressUpdate
                      publishProgress(message);
                  }
              });
              mTcpClient.run();
  
              return null;
          }
  
          @Override
          protected void onProgressUpdate(String... values) {
              super.onProgressUpdate(values);
  
              //in the arrayList we add the messaged received from server
              arrayList.add(values[0]);
              // notify the adapter that the data set has changed. This means that new message received
              // from server was added to the list
              mAdapter.notifyDataSetChanged();
          }
      }
  }
  </code></pre>