代码在if子句之后不起作用

时间:2016-05-11 14:24:22

标签: java if-statement

我是网络编程新手并写了一个聊天客户端。它几乎正常工作,但是当我突然添加if子句in.hasnext时,即使我的服务器实际上发送了一些东西,它也会返回false。

使用if子句:

    @Override
public void run() {
    while(!server.isClosed()){


        if(ChatClient.WriteListener.message!=null){
            String m = ChatClient.WriteListener.message;
            out.println(m);
            ChatClient.WriteListener.message = null;
        }

        if(in.hasNext()){
            System.out.println("hab");
            String message = in.next();
            textPane.setText(textPane.getText()+"\n"+message.replaceAll("_", " "));
        }
        out.flush();
    }
    System.out.println("closed");

}

没有if子句

public void run() {
    while(!server.isClosed()){          
        out.println(ChatClient.WriteListener.message);      
        if(in.hasNext()){
            System.out.println("hab");
            String message = in.next();
            textPane.setText(textPane.getText()+"\n"+message.replaceAll("_", " "));
        }
    }
    System.out.println("closed");

}

创建进出:

    public UserThread(Socket s){
    server = s;
    try {
        out = new PrintWriter( server.getOutputStream(), true );
        in  = new Scanner( server.getInputStream() );
    } catch (IOException e) {
        e.printStackTrace();
    }
}

WriteListener

public static class WriteListener implements ActionListener {
    JTextField text;
    static String message;
    public WriteListener(JTextField jtf){
        text = jtf;
    }
    public void actionPerformed(ActionEvent ev) {       
        message = text.getText();
    }
  }

1 个答案:

答案 0 :(得分:1)

您的代码存在问题:

if (ChatClient.WriteListener.message!=null){
        String m = ChatClient.WriteListener.message;
        out.println(m);
        ChatClient.WriteListener.message = null;
}

您的out是实例PrintWriter(OutputStream out, boolean autoFlush)。当您在第一个out.println(m)语句if中调用PrintWriter时,在Socket上刷新缓冲区/流,导致您的第二个if(in.hasNext())语句返回false因为您的I / O套接字由PrintWriter自动关闭。您需要在true的初始化中更改/删除PrintWriter,如下所示:

try {
    out = new PrintWriter( server.getOutputStream());
    in  = new Scanner( server.getInputStream() );
} catch (IOException e) {
    e.printStackTrace();
}

JavaDoc:PrintWriter(OutputStream out, boolean autoFlush)