首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getOutputstream() jssc getInputStream()

getOutputstream() jssc getInputStream()
EN

Stack Overflow用户
提问于 2017-02-20 18:02:57
回答 1查看 1.5K关注 0票数 0

我使用jssc库通过串口与设备通信。在标准的java SerialComm库中,有两个方法getInputStream()和getOutputStream()。

为什么我需要这个?我想根据this示例实现Xmodem,xmodem构造函数需要两个参数:

代码语言:javascript
复制
public Xmodem(InputStream inputStream, OutputStream outputStream) 
{
     this.inputStream = inputStream;
     this.outputStream = outputStream;
}


Xmodem xmodem = new Xmodem(serialPort.getInputStream(),serialPort.getOutputStream());

在jssc中没有这样的方法,但我想知道是否有其他方法?

EN

回答 1

Stack Overflow用户

发布于 2017-03-16 15:43:54

一种可能是提供一个自定义PortInputStream类来扩展InputStream并实现JSSCs SerialPortEventListener接口。该类从串行端口接收数据,并将其存储在缓冲区中。它还提供了一个从缓冲区获取数据的read()方法。

代码语言:javascript
复制
private class PortInputStream extends InputStream implements SerialPortEventListener {
  CircularBuffer buffer = new CircularBuffer(); //backed by a byte[]

  @Override
  public void serialEvent(SerialPortEvent event) {
    if (event.isRXCHAR() && event.getEventValue() > 0) {
     // exception handling omitted
     buffer.write(serialPort.readBytes(event.getEventValue()));
    }
  }

 @Override
 public int read() throws IOException {
  int data = -1;
  try {
    data = buffer.read();
  } catch (InterruptedException e) {
    // exception handling
  } 

  return data;
}

@Override
public int available() throws IOException {
  return buffer.getLength();
}

类似地,您可以提供一个扩展OutputStream并写入串行接口的自定义PortOutputStream类:

代码语言:javascript
复制
private class PortOutputStream extends OutputStream {

  SerialPort serialPort = null;

  public PortOutputStream(SerialPort port) {
    serialPort = port;
  }

  @Override
  public void write(int data) throws IOException,SerialPortException {
    if (serialPort != null && serialPort.isOpened()) {
      serialPort.writeByte((byte)(data & 0xFF));
    } else {
      // exception handling
  }
  // you may also override write(byte[], int, int)
}

在实例化Xmodem对象之前,必须创建两个流:

代码语言:javascript
复制
// omitted serialPort initialization
InputStream pin = new PortInputStream();
serialPort.addEventListener(pin, SerialPort.MASK_RXCHAR);
OutPutStream pon = new PortOutputStream(serialPort);

Xmodem xmodem = new Xmodem(pin,pon);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42341530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档