Accepting Multiple Clients in Java TCP and make each client wait for 5 minutes

i am trying to make a TCP server In java that accepts 10 clients, each client should be treated on thread so no clients are waiting. Each thread will receive the client and make him wait for 5 minutes.

here's my so far code;

public class ThreadServer {

static class ServerThread implements Runnable {
Socket client = null;
public ServerThread(Socket c) {
    this.client = c;
}
public void run() {
    try {
        System.out.println("Connected to client : "+client.getInetAddress().getHostName());
        client.close();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}
}
public static void main(String args[]) {
    try {
        ServerSocket server = new ServerSocket(8787);
        while (true) {
            Socket p = server.accept();
            new Thread(new ServerThread(p)).start();
        }
    } catch (Exception ex) {
        System.err.println("Error : " + ex.getMessage());
    }
}

}

Answers


This can be solved easily with a ScheduledExecutorService like this:

public class RespondLater implements Runnable {

  final Socket client;

  public RespondLater(final Socket c) {
    this.client = c;
  }

  public void run() {
    try {
      System.out.println("5 minutes later on client: " + client.getInetAddress().getHostName());
      // do whatever you want with the client 5 minutes later here
    } catch (Exception e) {
      System.err.println(e.getMessage());
    } finally {
      try {
        client.close();
      } catch (Exception ex) {
      }
    }
  }

  public static void main(String[] args) {
    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    try (final ServerSocket server = new ServerSocket(8787)) {
      while (true) {
        final Socket p = server.accept();
        executor.schedule(new RespondLater(p), 5, TimeUnit.MINUTES);
      }
    } catch (Exception ex) {
      System.err.println("Error : " + ex.getMessage());
    } finally {
      executor.shutdownNow();
    }
  }
}

Please note that there are never more than Runtime.getRuntime().availableProcessors() threads active, so you can have this construct handle probably thousands of connections.

I assume however that most clients will time-out before the 5 minute mark is reached.


Need Your Help

What's the goal of using CMS or Framework instead of PHP programming

php frameworks content-management-system

Firstable i hate CMS, i tryed drupal and joomla once upon a time but i couldn't understand a thing! Everyone i talk with seem to claim that today you cannot develop a website without a CMS..

.htaccess doesn't rewrite relative to the root directory

.htaccess mod-rewrite

I have tried to create an .htaccess file to do following: