Java Swing中的错误发布()/进程()交互

时间:2017-08-25 16:14:44

标签: java swing swingworker

我正在用java编写在线视频游戏。我已经完成了服务器,现在我已经到了客户端。 我的问题在于套接字侦听器代码中的某个地方,一个swingworker子类,其工作是监听服务器(doInBackGround())并根据需要更新游戏地图。

以下是代码:

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();
    }
}

根据三个调试println(),当播放器移动并且服务器将其广播到所有客户端时,消息被读取并发布但从未处理过。怎么会这样?

1 个答案:

答案 0 :(得分:2)

您要在for循环 - list.remove(0)中删除列表中的邮件两次:

for(String msg = list.remove(0); list.size() != 0; msg = list.remove(0))

这是迭代列表的简单方法:

for(String msg : list){
    System.out.println(msg);
}