繁体   English   中英

Java TCP FIN但没有instream eof

[英]Java TCP FIN but no instream eof

我一直在使用org.apache.commons.net.telnet连接到控制流并向相机发送命令。 我发送一个数据流请求并打开一个新线程,该线程扫描来自相机传感器的图像并将数据作为原始字节发送给我。 我正在使用标准的 java.io 内流和外流来读取。 我正在写入文件的外流......只是原始字节。 但是,我陷入了读取套接字发送数据的无限循环中。 A instream.read() > -1 让我在那里...我已经完成了instream.available() > 0 ,但这通常会缩短图像(可以理解)。 我什至尝试过各种和/或但永远无法完整阅读。

我已经在 Wireshark 中确认一切都通过我的程序并发送了一个 FIN,但由于某种原因,JAVA 没有拿起 FIN 并给我 -1。 文件的输出保持打开状态,我从未从传感器获得“完整”的图像扫描。 (我一直在手动终止流并读取图像。最终目标是将此图像放入标签中,并将其用于即时相机曝光更新。)

有什么方法可以检测 FIN 消息并告诉循环在instream.read()之外instream.read()

其他信息:Win 7(企业版)、Netbeans IDE

一个instream.read() > -1让我在那里

当然可以。 它丢弃了一个字节,它首先不是一个有效的测试。 您的读取循环应如下所示:

int ch;
while ((ch = instream.read()) != -1)
{
    // ... Cast ch to a byte and use it somehow ...
}

或这个:

int count;
byte[] buffer = new byte[8192];
while ((count = instream.read(buffer)) > 0)
{
    // ...
    // for example:
    out.write(buffer, 0, count);
}
  1. 以为你的流读码很特别,不能放出来? 我不信。

  2. .available()不是流结束的测试。 它只返回您可以安全读取的字节数,而不会被阻止等待传入数据。

  3. 图像数据结束后,您从流中得到了什么?

  4. 这是InputStream用法的示例,我 100% 确定它是有效的并且可以正确处理eof -s、异常和流关闭等:

     static final int BUFFER_SIZE = 1024 * 32; public static ByteBuffer buffer(InputStream stream) throws IOException { // try (<resourse>) to properly handle 'stream.close()` try (BufferedInputStream reader = new BufferedInputStream(stream)) { byte[] buffer = new byte[BUFFER_SIZE]; ByteBuffer result = ByteBuffer.allocate(BUFFER_SIZE); int totalReaded = 0, readed; while ((readed = reader.read(buffer)) >= 0) { if (readed > result.remaining()) { // well, we've exceeded capacity of given buffer, make it grow ByteBuffer t = result; result = (ByteBuffer) ByteBuffer.allocate((int)((totalReaded + readed) * 1.3)); result.put(t.array(), 0, totalReaded); } totalReaded += readed; result.put(buffer, 0, readed); } return ByteBuffer.wrap(result.array(), 0, totalReaded); } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM