日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/15 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 记录一次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(); }

?

總結

以上是生活随笔為你收集整理的记录一次Socket编程:OutputStream的flush方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。