标签:java character socket buffer
目前在学习Socket,因为和IO关系紧密,于是顺便也学了下IO
发现有这样一句话:
The flush method is valid on any output stream,but has no effect unless the stream is buffered
这句话意思是所有的输出流都有flush方法,但是仅对缓冲流有效
看到这里,笔者想到了自己写的serversocket类,部分代码如下,没有用buffered流也调用了flush方法啊?于是进行了一番探讨
private OutputStream ous; ous = socket.getOutputStream(); public void sendMsg(String msg){ PrintWriter out = new PrintWriter(ous); out.println("消息:"+msg); out.flush(); }
让我们来看一下PrintWriter的底层代码,部分相关代码如下
public class PrintWriter extends Writer { protected Writer out; private final boolean autoFlush; /** * Creates a new PrintWriter, without automatic line flushing. * * @param out A character-output stream */ public PrintWriter (Writer out) { this(out, false); } /** * Creates a new PrintWriter. * * @param out A character-output stream * @param autoFlush A boolean; if true, the <tt>println</tt>, * <tt>printf</tt>, or <tt>format</tt> methods will * flush the output buffer */ public PrintWriter(Writer out, boolean autoFlush) { super(out); this.out = out; this.autoFlush = autoFlush; lineSeparator = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("line.separator")); } public PrintWriter(OutputStream out) { this(out, false); } }如上所示,这样我们就很清楚了,当调用包装OutputStream的构造方法时,autoFlush参数是falus
标签:java character socket buffer
原文地址:http://blog.csdn.net/ytingone/article/details/41039757