Search code examples
javamultithreadingrunnable

Multi Thread Java Server


am currently working on a project where I have to build a multi thread server. I only started to work with threads so please understand me.

So far I have a class that implements the Runnable object, bellow you can see the code I have for the run method provided by the Runnable object.

public void run() {

    while(true) {
        try {
            clientSocket = serversocket.accept();

            for (int i = 0; i < 100; i++) {
                DataOutputStream respond = new DataOutputStream(clientSocket.getOutputStream());
                respond.writeUTF("Hello World! " + i);
                try {
                    Thread.sleep(1000);
                } catch(InterruptedException e) {
                  //
                }
            }
        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Bellow is the main method that creates a new object of the server class and creates a threat. initializing the Thread.

public static void main(String args[]) {
    new Thread(new Server(1234, "", false)).start();
}

I know this creates a new thread but it does not serve multiple clients at once. The first client need to close the connection for the second to be served. How can I make a multi threated server that will serve different client sockets at once? Do I create the thread on the clientSocket = serverSocket.accept();


Solution

  • yes.

    from the docs:

    Supporting Multiple Clients

    To keep the KnockKnockServer example simple, we designed it to listen for and handle a single connection request. However, multiple client requests can come into the same port and, consequently, into the same ServerSocket. Client connection requests are queued at the port, so the server must accept the connections sequentially. However, the server can service them simultaneously through the use of threads—one thread per each client connection.

    The basic flow of logic in such a server is this:

    while (true) {
        accept a connection;
        create a thread to deal with the client;
    }
    

    The thread reads from and writes to the client connection as necessary.

    https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html