簡體   English   中英

Client中的while循環有什么問題?

[英]What's wrong with my while loop in Client?

我有循環問題。 在我的項目中,我通過套接字從匹配發送評論。 我知道我的一個循環出了問題,因為在客戶端中最后的評論仍然會打印出來。

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        while(true){
        out.println(rel.getCommentary());

        }

getCommentary是一種方法,具有來自JTextField的當前注釋

客戶循環

        in = new Scanner(socket.getInputStream());          
        while(in.hasNextLine()){
            showCommentary(in.nextLine());
        }

服務器GUI

public void actionPerformed(ActionEvent e) {

        Object source = e.getSource();

        if(source == addComment){

            String comment=commentField.getText();
            rel.setCommentaryText(comment);  
            panel4.setBackground(Color.green);

        }

客戶

private void showCommentary(String text){
    showArea.append(text+ "\n");
    showArea.setCaretPosition(showArea.getDocument().getLength());
}

關系類

public class Relation{

    String relation;

    public Relation() {

    }

     public void setCommentaryText(String relation){
         this.relation= relation;
     }

    public String getCommentary(){
        return this.relation;
    }

}

好吧,在Server ,您應該有一個可以打印注釋的方法:

public void printCommentary(String commentary) {
    out.println(commentary);
}

ServerGUI ,設置注釋時:

if (source == addComment) {
    String comment= commentField.getText();
    //call the server's print method we just wrote, only once, no loop!
    server.printCommentary(comment);
}

您的錯誤是while(true)循環一直在執行。 它將打印以永久輸出您最后的評論。 你不應該那樣做。

暫無
暫無

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

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