记录一次Socket编程:OutputStream的flush方法

先上源码:

 /**
     * Flushes this output stream and forces any buffered output bytes
     * to be written out. The general contract of <code>flush</code> is
     * that calling it is an indication that, if any bytes previously
     * written have been buffered by the implementation of the output
     * stream, such bytes should immediately be written to their
     * intended destination.
     * <p>
     * If the intended destination of this stream is an abstraction provided by
     * the underlying operating system, for example a file, then flushing the
     * stream guarantees only that bytes previously written to the stream are
     * passed to the operating system for writing; it does not guarantee that
     * they are actually written to a physical device such as a disk drive.
     * <p>
     * The <code>flush</code> method of <code>OutputStream</code> does nothing.
     *
     * @exception  IOException  if an I/O error occurs.
     */
    public void flush() throws IOException {
    }

总结有以下几点:

1. flush()下达一条命令给缓冲区,让它将所储存的数据全部清空,即发送给下一级

2. flush()刷空输出流,并输出所有被缓存的字节。由于某些流支持缓存功能,该方法将把缓存中所有内容强制输出到流中。

3. OutputStream.flush()方法将所有写入到OutputStream的数据冲刷到相应的目标媒介中。比如,如果输出流是FileOutputStream,那么写入到其中的数据可能并没有真正写入到磁盘中。即使所有数据都写入到了FileOutputStream,这些数据还是有可能保留在内存的缓冲区中。通过调用flush()方法,可以把缓冲区内的数据刷新到磁盘(或者网络,以及其他任何形式的目标媒介)中。

例子:

// 模拟浏览器,给tomcat服务端发送符合http协议的请求消息  
public static void main(String[] args) throws IOException
{
    Socket s = new Socket("127.0.0.1", 80);
    PrintWriter out = new PrintWriter(s.getOutputStream());
    out.println("GET /myweb/test.jsp HTTP/1.1");
    out.println("Accept: */*");
    out.println("Accept-Language: zh-CN");
    out.println("Accept-Encoding: gzip, deflate");
    out.println();
    out.flush(); // 清空缓存并输出流
    InputStream in = s.getInputStream();
    byte b[] = new byte[1024];
    int leng = 0;
    while((leng = in .read(b)) != -1)
    {
        String str = new String(b, 0, leng);
        System.out.println(str);
    }
    s.close();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值