Java - 了解PrintWriter并需要刷新 [英] Java - Understanding PrintWriter and need for flush

查看:244
本文介绍了Java - 了解PrintWriter并需要刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,首先我为所有代码道歉,但我觉得太多的代码比不够好。我正在制作一个简单的聊天客户端和编剧,特别是我正在努力。使用代码的方式现在它将与服务器类进行交互,并且非常精细并打印我想要打印的内容。但是,当我删除'writer.flush();'时,它将停止打印。由于我的理解 - 显然是错误的 - 'writer.println(outgoing.getText());'应该足够了,因为这会发送我试图发送到服务器的文本。我理解flush会强制写入所有信息,但为什么在我写完我想写的东西时需要这个?

Ok, firstly I apologise for all the code but I feel like too much code is better than not enough. I'm making a simple chat client and printwriter in particular i'm struggling with. With the code the way it is the now it will interact with the server class and perfectly fine and print what im wanting to print. However, when I remove 'writer.flush();' it will stop printing. With my understanding -which is evidently wrong- 'writer.println(outgoing.getText());' should be enough as this would send the text im trying to send to the server. I understand flush forces all the information to write but why is this required when i've already written what I want to write?

public class SimpleChatClientA {

JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;

public void go(){

    JFrame frame = new JFrame("Ludicrously Simple Chat Client");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel mainPanel = new JPanel();

    incoming = new JTextArea(15,50);
    incoming.setLineWrap(true);
    incoming.setWrapStyleWord(true);
    incoming.setEditable(false);

    JScrollPane qScroller = new JScrollPane(incoming);
    qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    outgoing = new JTextField(20);

    JButton sendButton = new JButton("Send");
    sendButton.addActionListener(new SendButtonListener());

    mainPanel.add(qScroller);
    mainPanel.add(outgoing);
    mainPanel.add(sendButton);
    setUpNetworking();

    Thread readerThread = new Thread(new IncomingReader());
    readerThread.start();

    frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
    frame.setSize(400, 500);
    frame.setVisible(true);


}//close go

public void setUpNetworking(){
    try{

        sock = new Socket("127.0.0.1", 5000);

        InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());

        reader = new BufferedReader(streamReader);
        writer = new PrintWriter(sock.getOutputStream());
        System.out.println("network established");
    }catch(Exception e){
        e.printStackTrace();
    }
}//close setupnetworking

public class SendButtonListener implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {

        try{
            writer.println(outgoing.getText());
            writer.flush();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        outgoing.setText("");
        outgoing.requestFocus();
    }

}//close sendbuttonlistener inner class


public class IncomingReader implements Runnable{

    public void run(){
        String message;
        try{

            while((message = reader.readLine()) != null){
                System.out.println("read " + message);
                incoming.append(message + "\n");
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }

}//close inner class incomingreader


public static void main(String[] args){
    new SimpleChatClientA().go();
}

}

在此先感谢,如果有更多信息我可以给我第一次正确发布到stackoverflow请告诉我。

Thanks in advance, if there is anymore information I can give please let me know first time i've properly posted to stackoverflow.

推荐答案

println() PrintWriter 类的方法仅在<$ c时将数据提交到流中$ c> autoFlush 属性已启用。

The println() methods of the PrintWriter class "commit" the data to the stream only if the autoFlush attribute is enabled.

从Java文档中看这个引用:

Look at this quote from the Java docs:


如果自动刷新是启用它将仅在调用println,printf或format方法之一时完成

if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked

此处链接到Java文档: https:/ /docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.OutputStream,%20boolean)

Link to Java docs here: https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.OutputStream,%20boolean)

如果您需要将消息发送到服务器,请在打开autoflush选项的情况下创建 PrintWriter 对象。

If you need to send the message over to the server, then create the PrintWriter object with the autoflush option turned on.

那么,在你创建作家对象的地方,只需这样做:

So, where you're creating the writer object, just do this:

writer = new PrintWriter(sock.getOutputStream(),true);

应该这样做。希望它有所帮助!

That should do it. Hope it helps!

这篇关于Java - 了解PrintWriter并需要刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆