title: How can I handle multiple clients connected to a server using sockets?
body: <p>I have an Android app that needs to let multiple devices connect. One device should act as the group owner and issue instructions to all of the clients to do specific things. I suppose it's comparable to a wireless handheld game where one player is the host.</p>
  
  <p>I have a couple of questions so I will try to keep them concise. Even an answer to just the first would help.</p>
  
  <p>First, I've successfully paired a single server and single client phone using sockets. I did this using Android's Wi-Fi Direct technology (<a href="http://developer.android.com/guide/topics/connectivity/wifip2p.html">Described here</a>). The tutorial is helpful but unfortunately not very thorough, particularly in describing one-to-many connections. Once a peer list is found, socket connections can be opened. I was able to connect two devices using a thread for the server (<a href="http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/">Using this example</a>), like so:</p>
  
  <pre><code>public class ServerThread implements Runnable {
  
          public void run() {
               (Code...)
               client = serverSocket.accept();
               (...other code here.)
          }
  }
  </code></pre>
  
  <p>A client is created following a button press (I think, still trying to get my head around my modified code):</p>
  
  <pre><code>public class MusicClientThread implements Runnable {
       Socket socket = new Socket(serverAddr, port);
       while (connected) {
            //(Other code here.)
            while ((line = in.readLine()) != null) {
            //While there are still messages coming
            }
       }
       socket.close();
       //(Other code here too.)
  }
  </code></pre>
  
  <p>So I suppose my first question is: How would I allow more clients to be connected? My ServerThread refers to a single client variable above so I do not see how I would allow a varying number (my application is aiming for anything from 2 to 10 users) nor do I know the correct way to differentiate between all my different clients. My only guess is that I would use the unique IP address of each phone.</p>
  
  <p>My 2nd question is, once I've established a connection with multiple clients/peers, how would I then send and receive instructions to them correctly? Currently my single server awaits an instruction, and upon receiving it, issues a response instruction. I need it so that the server can send instructions from the start, using button presses, and the result of these is visible on the client devices.</p>
  
  <p>I hope I have made everything clear!</p>