ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-为DataInputStream手动设置超时

2019-12-08 22:02:57  阅读:758  来源: 互联网

标签:network-programming java


我正在两个站(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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有