title: Java Sockets: One Server and Multiple Clients
body: <p>So I created a basic client-server program in java. It starts out like this:</p>
  
  <ol>
  <li>Client connects to Server</li>
  <li>Server asks for Client's name</li>
  <li>Client responds with name</li>
  <li>Server greets Client</li>
  <li>After this, Client speaks and the Server repeats the words back</li>
  </ol>
  
  <p>I got this to work without too much trouble using <a href="http://www.tutorialspoint.com/java/java_networking.htm">this tutorial</a>. The problem comes whenever I try to introduce multiple clients. I thought that it would work because I'm using multiple threads, however, the second clients just hangs until the first client quits and then it starts it work (the server does accept input from the second client, but it doesn't respond with anything until the first client quits).</p>
  
  <p>Here is the code I'm using: </p>
  
  <pre><code>import java.net.*;
  import java.io.*;
  
  public class Server extends Thread {
    private ServerSocket listener;
  
    public Server(int port) throws IOException {
      listener = new ServerSocket(port);
    }
  
    public void run() {
      while(true) {
        try {
          Socket server = listener.accept();
          DataOutputStream out = new DataOutputStream(server.getOutputStream());
          out.writeUTF("What is your name?");
          DataInputStream in = new DataInputStream(server.getInputStream());
          String user_name = in.readUTF();
          out.writeUTF("Hello "+user_name);
          while(true) {
            String client_message = in.readUTF();
            out.writeUTF(client_message);
          }
        }
        catch(IOException e) {
          e.printStackTrace();
        }
      }
    }
  
    public static void main(String[] args) {
      int port = 6006;
      try {
        Thread t = new Server(port);
        t.start();
      } catch(IOException e) {
        e.printStackTrace();
      }
    }
  }
  </code></pre>
  
  <p>Can someone explain what I'm doing wrong?</p>
  
  <p>I have looked at the using Runnable instead of Extends Thread, but I ran into even more problems there, so I want to try and work with this first.</p>