multithreading - Accepting Multiple Clients in Java TCP and make each client wait for 5 minutes -
i trying make tcp server in java accepts 10 clients, each client should treated on thread no clients waiting. each thread receive client , make him wait 5 minutes.
here's 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 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()); } }
}
this can solved scheduledexecutorservice 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()); // whatever want client 5 minutes later here } catch (exception e) { system.err.println(e.getmessage()); } { 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()); } { executor.shutdownnow(); } } }
please note there never more runtime.getruntime().availableprocessors()
threads active, can have construct handle thousands of connections.
i assume clients time-out before 5 minute mark reached.
Comments
Post a Comment