簡體   English   中英

異步和同步模式下SocketChannel.read()的區別?

[英]The difference of SocketChannel.read() in async and sync mode?

我知道Java NIO有兩種模式,異步模式和同步模式。當我閱讀SocketChannel.read()的javadoc時,得到以下解釋:

Reads a sequence of bytes from this channel into the given buffer. 
An attempt is made to read up to r bytes from the channel, where r is the number of bytes remaining in the buffer, that is, dst.remaining(), at the moment this method is invoked. 

Suppose that a byte sequence of length n is read, where 0 <= n <= r. This byte sequence will be transferred into the buffer so that the first byte in the sequence is at index p and the last byte is at index p + n - 1, where p is the buffer's position at the moment this method is invoked. Upon return the buffer's position will be equal to p + n; its limit will not have changed. 

A read operation might not fill the buffer, and in fact it might not read any bytes at all. Whether or not it does so depends upon the nature and state of the channel. **A socket channel in non-blocking mode, for example, cannot read any more bytes than are immediately available from the socket's input buffer; similarly, a file channel cannot read any more bytes than remain in the file. It is guaranteed, however, that if a channel is in blocking mode and there is at least one byte remaining in the buffer then this method will block until at least one byte is read.** 

This method may be invoked at any time. If another thread has already initiated a read operation upon this channel, however, then an invocation of this method will block until the first operation is complete. 

是讓我感到困惑的是異步讀取和同步讀取的解釋。是的,在異步模式下,它將立即讀取緩沖區中已經存在的內容並返回。但是在同步模式下,它是不一樣的嗎?如果緩沖區中有東西,為什么不閱讀並立即返回?等待什么呢?

如果緩沖區中有東西,為什么不讀取它並立即返回?

我認為您理解錯了。 正如在文檔中所說的int read(ByteBuffer dst)

要將字節傳送到的緩沖區。

通道讀取字節並將其寫入緩沖區。

但是,可以確保,如果通道處於阻塞模式並且緩沖區中至少有一個字節剩余,則此方法將阻塞直到讀取至少一個字節。

at least one byte remaining in the buffer意味着緩沖區仍具有可用空間。 布爾值hasRemaining()和int missing()函數用於檢查此內容。

等什么?

等待從通道讀取一些字節或到達流的末尾。 在阻塞通道上讀取無法返回0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM