简体   繁体   English

Client中的while循环有什么问题?

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

I've got problem with loop. 我有循环问题。 In my project I'm sending a comments from match through socket. 在我的项目中,我通过套接字从匹配发送评论。 I know that something is wrong with one of my loops because in client last comment is still printed. 我知道我的一个循环出了问题,因为在客户端中最后的评论仍然会打印出来。

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

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

        }

getCommentary is a method with present comment from JTextField getCommentary是一种方法,具有来自JTextField的当前注释

Client's loop 客户循环

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

Server GUI 服务器GUI

public void actionPerformed(ActionEvent e) {

        Object source = e.getSource();

        if(source == addComment){

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

        }

Client 客户

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

Relation class 关系类

public class Relation{

    String relation;

    public Relation() {

    }

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

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

}

Well, in Server , you should have a method that will print commentary: 好吧,在Server ,您应该有一个可以打印注释的方法:

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

In ServerGUI , when you set the 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);
}

Your bug is that the while(true) loop is executing all the time. 您的错误是while(true)循环一直在执行。 It prints to outputstream your last commentary forever. 它将打印以永久输出您最后的评论。 You shouldn't do that. 你不应该那样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM