Java Socket輸入資料流如何檢測到EOF

來源:互聯網
上載者:User

對於InputStream的 read(b, off, len) 方法 public int read(byte[] b, int off, int len) throws IOException,Javadoc的說明為:

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available becausethe stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

The default implementation of this method blocks until the requested amount of input data len has been read,end of file is detected, or an exception is thrown.

那麼對於服務端Socket的輸入資料流來說,什麼是 end of file - EOF?首先說明一點,沒有所謂的標識字元是EOF,對於位元組流來說,從0~255的每個位元組都是正常的資料,EOF只是輸入資料流的一種狀態。

當Socket用戶端關閉的時候,服務端輸入資料流在讀完所有資料之後就會檢測到EOF,然後服務端輸入資料流返回-1。如果用戶端Socket沒有關閉,並且沒有資料可讀取的情況下,read方法會阻塞,等待有資料可讀。如果設定了SoTimeout,那麼直到逾時拋出異常,如果沒有設定逾時,那麼會一直等待資料到達。
通過測試,用戶端關閉Socket之後,服務端還可以重複讀取,每次都返回-1。

作者:csdn部落格 kingspider-sh

更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.