title: Listening to two ports simultaneously in Java server using multithreading
body: <p>I am building a simple Java server which simultaneously listens for client request on two ports simultaneously using two ServerSocket instances. Here is the code for Server:</p>
  
  <pre><code>import java.io.PrintWriter;
  import java.io.OutputStream;
  import java.net.ServerSocket;
  import java.net.Socket;
  
  class Socket1 implements Runnable
  {
      public void run()
      {
          try
          {
              ServerSocket serverSock=new ServerSocket(5000);
              while(true)
              {
                  Socket sock=serverSock.accept();
                  PrintWriter writer=new PrintWriter(sock.getOutputStream());
                  String text="Welcome to Port 5000";
                  writer.println(text);
              }
          }
          catch(Exception e)
          {
              System.out.println("Error");
          }
      }
  }
  
  class Socket2 implements Runnable
  {
      public void run()
      {
          try
          {
              ServerSocket serverSock=new ServerSocket(3000);
              while(true)
              {
                  Socket sock=serverSock.accept();
                  PrintWriter writer=new PrintWriter(sock.getOutputStream());
                  String text="Welcome to Port 3000";
                  writer.println(text);
              }
          }
          catch(Exception e)
          {
              System.out.println("Error");
          }
      }
  }
  
  public class Server
  {
      public static void main(String[] args)
      {
          Socket1 s1=new Socket1();
          Socket2 s2=new Socket2();
          Thread t1=new Thread(s1);
          Thread t2=new Thread(s2);
          t1.start();
          t2.start();
      }
  } 
  </code></pre>
  
  <p>Now code for Client1:</p>
  
  <pre><code>import java.io.InputStreamReader;
  import java.io.BufferedReader;
  import java.net.Socket;
  
  public class Client1
  {
      public static void main(String[] args)
      {
          try
          {
              Socket s=new Socket("127.0.0.1", 5000);
              InputStreamReader streamReader=new InputStreamReader(s.getInputStream());
              BufferedReader reader=new BufferedReader(streamReader);
              String text=reader.readLine();
              System.out.println(text);
              reader.close();
          }
          catch(Exception e)
          {
              System.out.println("Error");
          }
      }
  }
  </code></pre>
  
  <p>Client2 contains the same code as Client1, the only difference being that it tries to connect to port 3000. 
  Now, I execute Server.java first using command prompt. While the server blocks, I open two separate command prompts and execute Client1.java on one command prompt and Client2.java on the other command prompt. But, both clients go to blocking state and I get no output. Any idea how to solve this ? </p>