Reputation: 47
(UPDATE)So I am running a server and I want a certain number of clients to connect, so in the client class each time a client connects I increment a counter, but it does not seem to be working. I am trying to do it on the server side but its still not working
while(true){
try{
Socket clientSocket = serverSocket.accept();
MortgageRunnable m = new MortgageRunnable(clientSocket);
System.out.println("New player has connected!");
if(!(connectedClients == maxPlayers)){
new Thread(m).start();
connectedClients++;}
else{m.displayMessage("Max players connected");}
MortgageRunnable is basically the thread so all logic is there, and this is the function displayMessage():
public void displayMessage(String message) {
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(message);
}catch(IOException e){
e.getMessage();
}
Upvotes: 0
Views: 115
Reputation: 1187
Each time you create a new instance of Client it will re-initialize numofPlayers variable.
So, I'm going to assume you have another class which is CREATING these Client instances, let's just call that Main... I would store the counter in that 'Main' class which is spawning clients. Hopefully I understand your situation correctly.
class Main {
public static void main(String[] args) {
int numOfPlayers = 0;
if (numOfPlayers < maxPlayers) {
Client client = new Client();
numOfPlayers++;
}
}
}
Upvotes: 1