While loop not looping more than once in java
This won't loop more than once, so I am unable to check if I have a client message:
new Thread() {
public void run() {
while(true) {
for(int I=0; I<numPlayers; I++) {
if(!players[I].isConnected()) {
players[I].drop();
System.out.println("Client disconnected!");
players[I]=null;
readers[I]=null;
writers[I]=null;
numPlayers--;
}
try {
System.out.println(readers[I].ready());
if(readers[I].ready()) {
BufferedReader reader = readers[I];
System.out.println("Reading");
switch(reader.read()) {
case PacketID.Connect:
System.out.println("Connect");
players[I].name=reader.readLine();
PrintWriter writer=writers[I];
writer.write(PacketID.Connect);
writer.write(MaxPlayers);
writer.write(numPlayers);
for(int I2=0;I2<numPlayers;I2++){
writer.println(players[I2].name);
players[I2].sendMessage(
"Client "+players[I].name+" has connected!");
}
writer.flush();
开发者_运维百科 break;
case PacketID.Ready:
System.out.println("lolol lol");
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}.start();
I can see people saying my code is messy and inefficient. I'm going to clean it all up later Also I don't know why stack overflow is malformatting my code.
Your logic of looping on
for(int I=0;I<numPlayers;I++)
is flawed because it assumes no "holes" in the players array. What if you have 3 players connected (0,1,2) and player #0 disconnects? You'll decrement "numPlayers" and never look at player #2 again.
Also, you don't appear to be checking for null in your readers
and writers
array, so you no sooner set readers[I]=null
then you start trying to reference it.
...
readers[I]=null;
writers[I]=null;
numPlayers--;
}
try {
System.out.println(readers[I].ready());
...
Odds are you're throwing a null pointer exception somewhere in all this, and not seeing it because you're running the whole thing in a thread.
reader.read()
might be blocking for input
Some misplaced break statement might be breaking out of the while loop.
Your code does look correct as far the while loop goes. Are there any exceptions being thrown. That will be only reason.
I have not run your example but my thought process is as follows - the thread starts and runs to completion. That is why I asked if you can try to run the code without the thread. That may help you isolate your issue. cheers
Based on the print out (Hi false ..), I think readers[i].ready() is actually returning false and that is what stopping you from reading. I am not sure who sets the "ready" to be true. No exception, just simple dropping off the loop.. :)
I fixed it, using isConnected hung the server
Can you put the try in an else statement?
You probably don't want to read anything from the reader that is null
!
精彩评论