Java BufferedInputStream read()在没有从Stream读取一段时间后不接收数据

问题描述 投票:0回答:1

我写了一个应用程序来监听来自机器人的状态消息。我有一个与机器人打开的Socket连接。机器人不断发送我读取(和解析)的状态消息,以找出机器人完成当前任务的时间。

 /**
 * Listens on the Socket for RobotStateMessage (RSM). A RSM has messagetype 16  at byte[4]. The constructor of the RobotStateMessage class
 * throws an exception when the message is found to be corrupt. If that happens the method waits for the next uncorrupted message.
 *
 * @param command the robot state message is added to the command
 * @throws IOException
 * @throws GeneralURMessage_Parse_Exception
 * @throws TimeExpired_Exception
 */
public void executeRobotStateCommand(RobotStateCommand command) throws IOException, RobotStateMessage.GeneralURMessage_Parse_Exception, TimeExpired_Exception {
    byte[] data = new byte[3000];
    boolean run = true;
    RobotStateMessage message = null;
    long momentToQuit = System.currentTimeMillis() + 5000;
    while (run) {
        if (System.currentTimeMillis() > momentToQuit) {
            throw new TimeExpired_Exception(5000);
        }
        ur_in.read(data);
        int type = data[4];
        if (type == 16) {
            run = false;
            try {
                // contructor of RobotStateMessage parses the data
                message = new RobotStateMessage(data);
            } catch (RobotStateMessage.CorruptRobotStateMessage_Exception e) {
                // the message received form ur was corrupted , ignore and wait for next message
                run = true;
            }
        }

    }
    command.robotStateMessage = message;

}

当我停止从BufferedInputStream ur_in读取一段时间时,会出现问题。任何暂停时间超过一分钟,ur_in.read(data)在消耗所有缓冲的旧数据后阻塞。

在使用缓冲数据之后,BufferedInputStream上似乎没有新数据。使用第二个工具收听机器人的数据,我可以清楚地看到状态消息仍然是广播的。

Socket仍然存在但输入流似乎已“死亡”。我在套接字上设置了一个超时,以便read()不会永远阻塞,但这并没有解决我的问题,我在BufferdInputStream上没有收到更多的数据。

唯一有帮助的是重新连接套接字,这对我的问题来说不是一个令人满意的解决方案。

如何解决这个问题的任何帮助或建议表示赞赏。如果您需要更多信息,请询问。

java sockets inputstream
1个回答
0
投票

我假设您正在使用TCP。如果您没有从缓冲区中读取,则套接字会通知机器人停止传输,直到缓冲区有能力接收更多数据。机器人软件必须处理,不能写入任何数据,并可能断开客户端连接。您不应该使用套接字缓冲区来存储数据,而是尽可能快地将数据移动到其他缓冲区。设置更大的接收缓冲区可能会有所帮助,但不是一个好主意。

© www.soinside.com 2019 - 2024. All rights reserved.