Raghavendra Reddy
Raghavendra Reddy

Reputation: 31

How to keep track of the active clients in a multi client server application?

I want to know if there's a way to know the clients that are all connected to a server at any point of time. I am using Sockets/Java. i.e If there are 'n' number of clients to whom the server is listening to, then is it possible to keep track of the clients that are connected?? Apparently, isConnected() and isClosed() methods don't provide me a solution that i am looking for. Please help

Upvotes: 3

Views: 3348

Answers (3)

ja_mesa
ja_mesa

Reputation: 1969

Do you mean connected to the server or connected to your application? Under Unix/Windows use "netstat -a" to see all active connections and all listening ports. If you want at your app level then use a list or counter which increments in every accept and decrement when the socket is closed.

Upvotes: 0

Ravi Trivedi
Ravi Trivedi

Reputation: 2360

1) If you are creating multi client-server program then consider doing it as multithreaded client-Server program.

2) Create new Thread for each new client. This unique Thread creation will help you keep track of all the active client threads.

3) You can check the status of the client threads which have been created, as below:

Source >> http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.State.html

Thread.getState() will return 1 of the following Thread.State possible statuses:

NEW: A thread that has not yet started is in this state.

RUNNABLE: A thread executing in the Java virtual machine is in this state.

BLOCKED: A thread that is blocked waiting for a monitor lock is in this state.

WAITING: A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TIMED_WAITING: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

TERMINATED: A thread that has exited is in this state.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

I would do it this way

public class Test1 {
    static Collection<Socket> activeSockets = new ConcurrentLinkedQueue<>(); 

    static class Task implements Runnable {
        Socket sk;

        Task(Socket sk) {
            this.sk = sk;
        }

        public void run() {
            activeSockets.add(sk);
            try {
                ...
            } finally {
                activeSockets.remove(sk);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ExecutorService ex = Executors.newCachedThreadPool();
        ServerSocket server = new ServerSocket(5555);
        for (;;) {
            Socket sk = server.accept();
            ex.execute(new Task(sk));
        }
    }
}

Upvotes: 1

Related Questions