Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store Clients in a list

I am running a server, and I have an arraylist of type Client When a client connects through ServerSocket.accept() I pass the new Socket to the arraylists constructor. This is everything inside the constructor

this.add(new Client(Socket client));

My problem is when a client disconnects, it closes the Socket, but it doesn't delete its spot in the arraylist, and shift everything down one. So the arraylist is constantly growing bigger.

What can I do/use to fix this problem?

Sometimes I will run commands that will execute on all clients which is why I store the clients in an arraylist.

Is there a better alternative for storing clients in a server?

Update 1

The classes are in the beginning stages. Very little has been implemented. So far the HashMap option suggested in the answer works best for me. Thank you for your replies

like image 526
Loligans Avatar asked Apr 16 '15 20:04

Loligans


1 Answers

Interesting problem.

You should use hash map here .. Add the client with object as value and use some key. Whenever you disconnect it, remove it from the map.

A good question could me what should be the key? may be the object reference (depends on your choice) or anything that is unique with respect to client object (there must be something, if not, you can generate it easily).

Map<Integer,Client> clientMap = new HashMap<Integer,Client>();
like image 182
Danyal Sandeelo Avatar answered Oct 23 '22 09:10

Danyal Sandeelo