您可以将侦听器添加到 SerialPort,只要该端口上有数据可用,该侦听器就会收到通知。在此回调中,in.available()
还应该返回可以读取的字节数,但最好只消耗字节直到read
返回 -1。
final CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
final SerialPort com1 = (SerialPort)portId.open("Test", 1000);
final InputStream in = com1.getInputStream();
com1.notifyOnDataAvailable(true);
com1.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
com1.addEventListener(new SerialPortEventListener() {
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
byte[] buffer = new byte[4096];
int len;
while (-1 != (len = in.read(buffer))) {
// do something with buffer[0..len]
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});