java-为DataInputStream手动设置超时
作者:互联网
我正在两个站(A,B)之间建立标准的TCP连接
A正在发送消息,B正在接收并发送回响应,然后关闭连接.
> B站是“黑匣子”,我无法在那里进行更改或执行任何操作.
有时候,当B没有发送回响应时,我需要重试整个过程.
我想在A站的接收时间上设置超时(等待B的回答).
因此,基本上,当等待时间到期时,我将调度重试.
我没有找到一种方法来为DataInputStream设置超时. (仅用于整个套接字连接-我不想要)
一些代码:
/**
* Method receives the Server Response
*/
public byte[] receive(DataInputStream is) throws Exception
{
logger.debug(TAG + " Client Recieving...");
try
{
byte[] inputData = new byte[1024];
// here I want to set timeout for the "receiving mode"
is.read(inputData);
return inputData;
} catch (Exception e)
{
throw new Exception(TAG + " Couldnt receive data from modem: " + e.getMessage());
}
}
谢谢,
射线.
解决方法:
考虑使用非阻塞SocketChannel代替DataInputStream.
例:
private static final long TIMEOUT = 500;
/**
* Method receives the Server Response
*/
public <C extends SelectableChannel & ReadableByteChannel>byte[]
receive(C chan) throws IOException
{
logger.debug(TAG + " Client Recieving...");
try
{
Selector sel = Selector.open();
SelectionKey key = chan.register(sel, SelectionKey.OP_READ);
ByteBuffer inputData = ByteBuffer.allocate(1024);
long timeout = TIMEOUT;
while (inputData.hasRemaining()) {
if (timeout < 0L) {
throw new IOException(String.format("Timed out, %d of %d bytes read", inputData.position(), inputData.limit()));
}
long startTime = System.nanoTime();
sel.select(timeout);
long endTime = System.nanoTime();
timeout -= TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
if (sel.selectedKeys().contains(key)) {
chan.read(inputData);
}
sel.selectedKeys().clear();
}
return inputData.array();
} catch (Exception e)
{
throw new Exception(TAG + " Couldnt receive data from modem: " + e.getMessage());
}
}
标签:network-programming,java 来源: https://codeday.me/bug/20191208/2094370.html