St.Antario
St.Antario

Reputation: 27385

ServerSocket connection with more than one client

Folks. I'm newbie in network programming and come across the following issue. I need to write the server which can maintain a connection with more than one client simultaneously. What I've written is the following:

Main class:

public class Main {
    public static void main(String args[]) throws Exception{
        ConnectionUtils.waitForClients();
    }
}

ConnectionUtils class:

public class ConnectionUtils {

    private static ServerSocket server; 

    static{
        try {
            server = new ServerSocket(54321);
        } catch (Exception e) {
        }
    }

    private static Runnable acceptor = new Runnable() {
        @Override
        public void run() {
            try {
                Client c = new Client(server.accept());
                new Thread(acceptor).start();
                c.sendLine("Hello client \n");
            } catch (Exception e) {
            }
        }
    };

    public static void waitForClients(){
        Thread clientAcceptor = new Thread(acceptor);
        clientAcceptor.start();
    }
}

and it works, more-or-less. But what is the downside of that approach? I suspect there're too much disadvantage, but I can't catch their.

Upvotes: 0

Views: 180

Answers (2)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

The problem is that you creating an infinite number of threads where threads are expensive resources. You should be using a ThreadPool to limit the number of threads created in your program. Consider using Executors instead of using this low-level code, In Oracle documentation about Executors, there is an example similar to what you doing. Check it out!

Upvotes: 2

Joeblade
Joeblade

Reputation: 1743

Heh interesting. I wouldn't expect it to be wrong but it sure isn't how I'd write it. I'd probably have 1 thread in an infinite (semi-infinite with stop condition) loop that accepts and spawn threads, rather than something that looks like a recursive method but isn't. However as far as I can see it's not wrong.

Having said that, if you don't use your main thread for anything, why not do something like (and keep in mind i'm not a network programmer either)

public class ConnectionUtils {
    protected boolean stop = false;
    public static void waitForClients() {
        while (!stop) {
            Client c = new Client(server.accept());
            new Thread(new ClientDelegate(c)).start();
        }
    }
}

public static class ClientDelegate implements Runnable {
    private Client client;
    public ClientDelegate(Client c) { this.client = c; }
    public static void run() {
        c.sendLine("Hello client\n");
    }
}

Upvotes: 1

Related Questions