Java:Socket输入流没有接收新对象

时间:2015-01-06 15:58:17

标签: java sockets

在这里开始使用Java套接字。

我有一台服务器和一台客户端。客户端向服务器发送命令,例如“LIST_1”。然后,服务器将生成3个Edge对象的列表,并将它们发送到客户端。 如果命令是“List_2”,它将生成12个Edge对象的列表,“List_3”48等等。

我的问题是第一次有效。如果我发送“List_1”,我会得到一个返回的3个Edge对象的列表。但是,如果我然后发送命令“List_2”,我仍然只获得3个Edge对象的列表而不是12个。

我已尝试使用一些System.out.println进行调试。服务器似乎确实生成了包含12个Edge对象的正确列表,但客户端仍然接收到3个对象的相同(旧)列表。

服务器端:

private List<Edge> edges = new ArrayList<Edge>();

@Override
public void run() {
    try {
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream = socket.getInputStream();

        in = new ObjectInputStream(inStream);
        out = new ObjectOutputStream(outStream);

        boolean done = false;
        Object inObject = null;
        String welcome = "#Welcome message#";
        out.writeObject(welcome);
        System.out.println("Clientconnection has been made.");
        while (!done) {
            try {
                inObject = in.readObject();
                if (inObject instanceof String) {
                    String rawCommand = (String) inObject;   //[Command]_[Level] 
                    String[] splits = rawCommando.split("_");
                    String command = splits[0];
                    int level = Integer.parseInt(splits[1]);
                    kochfractal.setLevel(level);
                    System.out.println("Command received: " + command + ", level: " + level);
                    if (command.equals("EXIT")) {
                        done = true;
                    } else {
                        if (command.equals("LIST")) {
                        edges.clear();
                        kochfractal.generateEdges();
                        out.writeObject(edges);
                        out.flush();
                    }
                  }
                } else {
                    System.out.println("!Invalid command received!");
                }
            } catch (ClassNotFoundException e) {
                System.out.println("Object type not known");
            }
        }
        in.close();
        out.close();
        socket.close();

    } catch (IOException e) {

    }
}

客户方:

    public void sendCommandList(int level) throws IOException, ClassNotFoundException {
     String command = "LIST_" + Integer.toString(level);
     out.writeObject(command);
     System.out.println("Command send: " + commando);
     out.flush();
     List<Edge> edges = new ArrayList<Edge>();
     System.out.println("Reading List..");
     edges = (List<Edge>) in.readObject();
     System.out.println("List has been read. # of edges: " + edges.size());        
}

1 个答案:

答案 0 :(得分:0)

修正了它,添加了out.reset();在服务器端刷新之后。我觉得冲洗就足够了。