gpt4 book ai didi

java - 如何强制Java套接字的InputStream抛出IOException?

转载 作者:行者123 更新时间:2023-12-03 12:02:35 29 4
gpt4 key购买 nike

我正在测试在java.net.Socket之上构建的网络组件。我有这样的代码:

try {
byte[] buffer = new byte[1024]
int bytesRead = socket.getInputStream().read(buffer);
// more processing
} catch (IOException e) {
handleException(e);
}


如何强制 InputStream#read调用抛出 IOException,以便可以测试 handleException方法?我不想使用 mock 。我想使用实际的实现,并且只想使用Java API。

最佳答案

TLDR

从写法的角度来看,使用异常终止:

socket.setSoLinger(true, 0);
socket.close();

这将导致从另一端​​进行的任何后续读取都抛出 IOException
来自Oracle的 documentation的更多细节:

First, we need to distinguish the differences between an abortive and an orderly connection release. To understand this distinction we need to look at what happens at the TCP protocol level. It is helpful to imagine an established TCP connection as actually two separate, semi-independent streams of data. If the two peers are A and B, then one stream delivers data from A to B, and the other stream from B to A. An orderly release occurs in two stages. First one side (say A) decides to stop sending data and sends a FIN message across to B. When the TCP stack at B's side receives the FIN it knows that no more data is coming from A, and whenever B reads all preceding data off the socket, further reads will return the value -1 to indicate end-of-file. This procedure is known as the TCP half-close, because only one half of the connection is closed. Not surprisingly, the procedure for the other half is exactly the same. B sends a FIN message to A, who eventually receives a -1 after reading all preceding data sent by A off the socket.

By contrast, an abortive close uses the RST (Reset) message. If either side issues an RST, this means the entire connection is aborted and the TCP stack can throw away any queued data which has not been sent or received by either application.

So, how do Java applications perform orderly and abortive releases? Let's consider abortive releases first. A convention that has existed since the days of the original BSD sockets is that the "linger" socket option can be used to force an abortive connection release. Either application can call Socket.setLinger (true, 0) to tell the TCP stack that when this socket is closed, the abortive (RST) procedure is to be used. Setting the linger option has no immediate effect, except that when Socket.close() is called subsequently, the connection is aborted with an RST message. As we will see shortly, there are other ways that may cause a connection to be aborted, but this is the simplest way to make it happen.

关于java - 如何强制Java套接字的InputStream抛出IOException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62433263/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com