1

I am working on a project like HQ trivia where multiple clients connect to server and submit their answers for a question, for that i have written code in java where users connect to a ServerSocket and a new thread is created for each client. There can be hundreds of thousands of clients. while testing for only 100 clients server reaches to 95% of CPU usage. i have provided some of the code below. if anybody could help me with an efficient way of dealing with that much client would be really appreciated

Source for Main Class

public class Server {

            //static ServerSocket variable
            private static ServerSocket server;
            //socket server port on which it will listen
            private static int port = 9876;

   public static void main(String[] args) throws IOException, ClassNotFoundException {
        try {
        server = new ServerSocket(port);
        while(true){
            ClientWorker w;
            try{
                //server.accept returns a client connection
                System.out.println("Waiting for a connection to accept.");
                w = new ClientWorker(server.accept(), this);
                Thread t = new Thread(w);
                t.start();
                } catch (IOException e) {
                  System.out.println("Accept failed: 9876");
                  System.exit(-1);
                }
            }
        } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    }
}

Runnable Client Worker class

class ClientWorker implements Runnable {
    Server server;
    private Socket client;
    private String clientName = "";
    private String id = "";

    PrintStream printStream;
    BufferedReader bufferedReader;

    //Constructor
    ClientWorker(Socket client, Server server) {
        this.client = client;
        this.server= server;
    }

    @Override
    public void run() {
    try {
            bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            printStream = new PrintStream(client.getOutputStream());
            while(client.isConnected())
            {
                String message = bufferedReader.readLine();
                //Some logical operation on users message
                printStream.println("response");
            }
        }
    }
}

Server Specs are HDD: 451G CPU : 24 RAM: 16G

Thanks in advance for any help.

Faisal Asif
  • 199
  • 2
  • 15
  • 1
    You'll want a non-blocking implementation - use `SocketChannel` ([example](https://stackoverflow.com/a/24617983/2398375)) or a pre-existing framework like Netty. Also see the [C10k problem](https://en.m.wikipedia.org/wiki/C10k_problem). – Vince Jul 23 '19 at 18:00

0 Answers0