java-为DataInputStream手动设置超时
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-为DataInputStream手动设置超时,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1746字,纯文字阅读大概需要3分钟。
内容图文
![java-为DataInputStream手动设置超时](/upload/InfoBanner/zyjiaocheng/653/03201f66b5de4fcabef0f7f7fb1e958f.jpg)
我正在两个站(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());
}
}
内容总结
以上是互联网集市为您收集整理的java-为DataInputStream手动设置超时全部内容,希望文章能够帮你解决java-为DataInputStream手动设置超时所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。