Reputation: 141
I'm programming an online videogame in java. I've already done the server and now I'm onto the client. My problem lies somewhere in the socket listener code, a swingworker subclass whose job is to listen to the server (doInBackGround()) and update the game map as necessary.
Here's the code:
import javax.swing.*;
import java.util.List;
public class GameWorker extends SwingWorker<Void, String> {
private SocketStreamsBean streams;
private GameFrame game;
public GameWorker(SocketStreamsBean streams, GameFrame game) {
this.streams = streams;
this.game = game;
}
@Override
protected Void doInBackground() throws Exception {
for(String msg = streams.getIn().readLine(); msg != null; msg = streams.getIn().readLine()){
System.out.println("bp " + msg + " " + Thread.currentThread().getId());//TODO remove
publish(msg);
System.out.println("ap " + msg + " " + Thread.currentThread().getId());//TODO remove
}
return null;
}
@Override
protected void process(List<String> list) {
for(String msg = list.remove(0); list.size() != 0; msg = list.remove(0)) {
System.out.println("dp " + msg + " " + Thread.currentThread().getId());//TODO remove
String[] cmds = msg.split(":");
switch (cmds[0]) {
case "ADD":
game.add(cmds[1], cmds[2], cmds[3]);
break;
case "MOVE":
game.remove(cmds[1]);
game.add(cmds[1], cmds[2], cmds[3]);
break;
case "REMOVE":
game.remove(cmds[1]);
break;
case "BULLETS":
//game.addBullets(cmds[1]);
}
}
list.clear();
}
}
According to the three debug println() when a player moves and the server broadcast it to all the clients the message is read and published but never processed. How could it be?
Upvotes: 0
Views: 58
Reputation: 21233
You are removing messages from the list twice in for
loop - list.remove(0)
:
for(String msg = list.remove(0); list.size() != 0; msg = list.remove(0))
Here is a simple way to iterate a list:
for(String msg : list){
System.out.println(msg);
}
Upvotes: 2