marxin
marxin

Reputation: 3922

Java multi client server application - how to organise sockets

_Hey, I have a question. I want to write application which will have multiple chats, rooms etc. And now i have some troubles with server. My conception is to store data of clients in Vector of ClientSocket classes.

ClientSocket class will be like this:

public class ClientSocket {
    int client_id;
    Socket socket;
}

On main server thread:

ServerSocket serverSocket;
Vector<ClientSocket> sockets;

And the idea is: when new connection is established, make a new thread, pass sockets vector as a parameter, generate player id, iterate through vector elements, check if client_id exists, if not, set the id, if yes, generate next and do the same.

And where is the problem? Im worried about synchronization. What will happen, if two clients arrive at same time, and vector size will change in the meantime? Am i doing it correct? Maby there is a better idea to organise it?

Thanks in advance Marcin

// edit

I meant that situation, but i think i will use Peter Lawrey solution :

Situation

Upvotes: 0

Views: 1074

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533530

Since you need to look up the client by client_id I would use a Map. If you use a ConcurrentMap it will be thread safe.

ConcurrentMap<Integer, Socket> socketByClientIdMap = new ConcurrentHashMap<>();

// check if a client exists already,
if (socketByClientIdMap.containsKey(clientId))

//  add a socket by client id.
socketByClientIdMap.put(clientId, socket);

// get a socket for a client_id
Socket s = socketByClientIdMap.get(clientId);

Upvotes: 1

Cratylus
Cratylus

Reputation: 54074

What will happen, if two clients arrive at same time, and vector size will change in the meantime?

Since on a new connection you create a new thread (as you say in your post)

when new connection is established, make a new thread, pass sockets vector as a parameter

then you have 2 threads for the 2 clients that arrive at the same time.
As a result 2 threads operate on the Vector that you use.

Vector as a class is itself synchronized so there is no harm done.

But also Vector is considered a rather deprecated collection so perhaps you would want to use newer collection data structures like List which are unsynchronized though and will have to either use a syncronized wrapper offered from Collections or synchronize yourself.

Upvotes: 0

Related Questions