title: Socket Client/Server stop method in java
body: <p>This is the simple client/server socket app for my faculty project. First, the Server class should be run, and then if Client class runs - it prints out the IP address of the local machine and the port that's been used.</p>
  
  <p>I can't figure out one thing:</p>
  
  <blockquote>
    <p>How and WHERE to create a method in class that will close(stop) the Server? And
    how to make this like an event or something, for example if client
    sends "stop" it should somehow stop the server...</p>
  </blockquote>
  
  <p><strong>SERVER.JAVA</strong></p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  
  public class Server {
      public static void main(String[] args) {
          System.out.println("The server has been summoned.\n");
          System.out.println("The server is waiting for client to come...");
          try {
              ServerSocket servertest = new ServerSocket(2014);
              while (true) {
                  try {
                      Socket ser = servertest.accept();
                      new ThreadSer(ser).start();
                  } catch (IOException e) {}
              }
          } catch (IOException e) {System.err.println(e);}
      }
  
      public static class ThreadSer extends Thread {
          private Socket s;
          public ThreadSer(Socket s) {
              this.s = s;
          }
          @Override
          public void run() {
              try {
                String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
                          + s.getLocalPort() + "\r\n";
                  OutputStream out = s.getOutputStream();
                  out.write(response.getBytes());
              } catch (IOException e) { System.err.println(e); }
  }}}
  </code></pre>
  
  <p><strong>CLIENT.JAVA</strong></p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  
  public class Client {
  
      public static void main(String[] args) throws UnknownHostException, IOException {
          Socket socket = new Socket("localhost", 2014);
  
          new OutputThread(socket.getInputStream()).start();
      }
  
      public static class OutputThread extends Thread {
          private InputStream inputstream;
          public OutputThread(InputStream inputstream) {
              this.inputstream = inputstream;
          }
          @Override
          public void run() {
              BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
              while (true) {
                  try {
                      String line = input.readLine();
                      System.out.println(line);
                  } catch (IOException exception) {
                      exception.printStackTrace();
                      break;
                  }
              }
  }}}
  </code></pre>