outputStream.write有缓冲区溢出?

时间:2011-11-10 12:57:51

标签: java io

我正在尝试将byte[]发送到串口。但是outputstream.write(byte[]);仅在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库中的有效方法

    我对此有一些想法:

    • I溢出输出缓冲区,波特率为低电平以立即发送此数据
    • write(byte[])未将byte[]剪切为较小的片段

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

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

  • 1 个答案:

    答案 0 :(得分:0)

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

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

    请参阅here

    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方法的实现可能存在错误。

    相关问题