繁体   English   中英

outputStream.write有缓冲区溢出?

[英]outputStream.write has has buffer overflow?

我正在尝试将一个byte[]发送到串行端口。 但是outputstream.write(byte[]); 仅当byte[].length时才有效byte[].length包含少于约100个字节。

想知道:

  • 使用spring源工具套件(Eclipse)
  • JDK 1.7
  • DEFAULTBAUDRATE设置为9600
  • byte[]永远不会包含超过476个字节
  • NRSerial是一个库,提供“已故”vaxx.comm库的平台依赖版本
  • 没有硬件连接到串行端口
  • 我正在用一个应用程序嗅探串口(有点像wireshark)
  • 我还是学生所以代码可能很糟糕:P

    此代码有效:

     NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE); port.connect(); OutputStream outputStream = port.getOutputStream(); for(int i = 0; i<bytes.length; i++){ if(i%10==0){ Thread.sleep(1); } outputStream.write(bytes[i]); } outputStream.flush(); outputStream.close(); port.disconnect(); 

    优势:适用于所有系统
    缺点:可能会不必要地睡觉

    这样做:

     NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE); port.connect(); OutputStream outputStream = port.getOutputStream(); for(byte b : bytes){ outputStream.write(b); } outputStream.flush(); outputStream.close(); port.disconnect(); 

    优点:没有不必要的睡眠
    缺点:可能无法在快速系统上运行,因为它们可以更快地处理每个系统

    但是如果字节包含大约100个字节,则下面的代码将失败:

     NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE); port.connect(); OutputStream outputStream = port.getOutputStream(); outputStream.write(bytes); outputStream.flush(); outputStream.close(); port.disconnect(); 

    尽管write(byte[])是sun库中的有效方法

    我对此有一些想法:

    • 我溢出输出缓冲区,波特率为低电平,立即发送此数据
    • write(byte[])不会将byte[]切割成较小的块

    你可能想知道为什么我问这个问题,如果我有一个有效的解决方案。 好:

    我想知道我的哪个解决方案更好和/或是否有其他/更好的方法来做到这一点。 除了为什么要使用一个方法write(byte[])如果它的处理能力依赖于硬件(至少在JavaDoc中这样说?)

  • 假设我已经使用Google搜索了正确的代码,这看起来不像Java的问题,而是使用NRSerialPort库的实现。

    深入了解代码,我可以看到SerialOutputStream提供了OutputStream的实现,它根据是使用write(byte)还是write(byte[])方法调用两种不同的方法:

    看到这里

    protected native void writeByte( int b, boolean i ) throws IOException;
    protected native void writeArray( byte b[], int off, int len, boolean i ) 
        throws IOException;
    

    在不深入研究本机代码的情况下,我猜测writeArray方法的实现可能存在错误。

    暂无
    暂无

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

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