[英]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.