Reputation: 61
I have a multi-threaded server in Java, however I want to limit the number of connected clients to 2. It's a basic application, just being used for testing.
On my server I have an int userNo attribute that assigns clients the value of either 0 or 1.
My question is, is there a better way of handling this. I only want up to 2 clients to connect, and I want my application to ignore any further requests.
Pseduo code:
if(userNo == 0) {
this is player 1;
}
if (userNo == 1) {
this is player 2;
}
else {
do nothing
}
Upvotes: 0
Views: 70
Reputation: 807
I would do something like this:
int connectedClientCount = 0;
// ...
while(true) {
ServerSocket ss = ...
Socket s = ss.accept();
if(connectedClientCount == 2) {
// Do stuff to tell connected Client that he is rejected because of max clients...
} else {
connectedClientCount++;
// cool stuff...
}
}
and somewhere else in you code (which gets executed on client disconnect)
public void clientDisconnected() {
connectedClientCount--;
}
Because of sake of simplicity I don't use thread synchronization in this example..
Upvotes: 1