my app uses the Java serial comm api. From reading the docs the inputstream.read() method blocks if there is no data available.
I tried setting a timeout on the serialport object but the isReceiveTimeoutEnabled() methods returns false, indicating my driver does not natively support timeouts.
So what's the best way to implement a read timeout given the above?
Thanks, Fred
If its not working for you just toss that inputstream into a thread and implement your own time out. If it times out call close() on the stream to unblock and close that thread
You will need two threads.
A watchdog thread will monitor a reading thread and interrupt it when a timeout is detected.
Have the reading thread tell the watchdog thread that it's about to start reading, and when it completed a read.
Have the watchdog thread start a timer when a read begins and interrupt the reading thread when it times out or stop listening for a time out when the reading is complete.
Read up on Java threading if you're not familiar with it. It's easy to have multi-threading bugs.
您可以使用InputStream.available()方法检查下一个read()
是否会阻塞。
You can also use a SerialPortEventListener as a callback to get notified of newly available data and only call read when there is something to do.
final SerialPort serialPort = ...;
final InputStream in = serialPort.getInputStream();
serialPortal.notifyOnDataAvailable(true);
serialPort.addEventListener(new SerialPortEventListener() {
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
// read from InputSteam
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.