簡體   English   中英

Java:套接字輸入流不接收新對象

[英]Java: Socket inputstream not receiving new objects

在這里開始使用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());        
}

修復它,添加out.reset(); 在服務器端刷新之后。 我以為沖洗就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM