在Java TCP中接受多个客户端并使每个客户端等待5分钟

时间:2014-01-31 14:00:23

标签: java multithreading tcp connection udp

我正在尝试创建TCP服务器在接受10个客户端的java中,应该在线程上处理每个客户端,以便没有客户端等待。每个线程将接收客户端并让他等待5分钟。

这是我迄今为止的代码;

公共类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());
    }
}

}

1 个答案:

答案 0 :(得分:0)

使用ScheduledExecutorService可以轻松解决这个问题:

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();
    }
  }
}

请注意,永远不会有超过Runtime.getRuntime().availableProcessors()个线程处于活动状态,因此您可以让此构造处理数千个连接。

但我认为大多数客户在达到5分钟之前会超时。