开发者

How to handle timeout on read with Java comm API

my app uses the Java serial comm api. From reading the docs the inputstr开发者_StackOverfloweam.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.


You can check with the InputStream.available() method if the next read() will block or not.


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
        }
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜