title: How can I get my Server (running on another Thread) to be active forever?
body: <p>I'm trying to write a basic Java client-server program, where in my client starts a thread which launches a Server, writes a number to an output stream, then has the Server read in the stream and print out that number.</p>
  
  <p>My client:</p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  
  public class Client {
  
  public static void connect(int number) {
  
      String hostName = ""; // Enter local computer name here
      int portNumber = 4444;
  
      try ( 
          Socket clientSocket = new Socket(hostName, portNumber);
          PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      ) {
  
          out.println(number);
  
      } catch (UnknownHostException e) {
          System.err.println("Don't know host!");
          System.exit(1);
      } catch (IOException e) {
          System.err.println("IO Exception caught!");
          System.exit(1);
      }
  
  }
  
  public static void main(String[] args) {
  
      Thread t = new Thread(new Server());
      t.start();
  
      Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
      for (int i=0; i &lt; numbers.length; i++) {
          connect(numbers[i]);
      }
  
  }
  }
  </code></pre>
  
  <p>My server:</p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  
  public class Server implements Runnable {
  
      public void run() {
  
          int portNumber = 4444;
          boolean listening = true;
  
          try (
              ServerSocket serverSocket = new ServerSocket(portNumber);
              Socket clientSocket = serverSocket.accept();
              BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
          ) {
  
              String input = in.readLine();
              System.out.println(input);
  
          } catch (IOException e) {
              System.err.println("Could not listen on port 4444");
              System.exit(-1);
          }   
  
      }
  
  }
  </code></pre>
  
  <p>Right now, if I try to run my <code>Client</code> I get:</p>
  
  <pre><code>java Client
  1
  IO Exception caught!
  </code></pre>
  
  <p>I suspect that this is because my Server thread dies after it executes its <code>try</code> block. With my current code, I'd want my <code>Server</code> active for the length of my <code>Client</code>s for loop, but ideally I'd want my server to run forever, waiting for any changes to the input stream, and printing it out accordingly. </p>
  
  <p>How would I do this?</p>