将光标移到/点击文章中的句子上,可以查看译文。      显示繁体中文内容    显示简体中文内容

How to end inputstream.read in java
在java中,如何结束 inputstream.read

I am trying to read data from 5 devices connected serially.my Java code is running fine if the device is healthy, if not then inputstream.read() hangs the program and does not allow further execution.

I have tried using inputstream.available(), BufferedInputStream.. . but nothing works.

What i want to do is :if a device does not respond my code, it should end itself and let the control go to the main program where it will go to the next device.the socket remains open for one cycle of polling.


Socket es = new Socket("10.12.90.153",4001); 
OutputStream osnew= es.getOutputStream(); 
InputStream isnew = new BufferedInputStream(es.getInputStream()); 

This is done in the task program, then i pass osnew and isnew to each device at a gap of one second for further action.the osnew writes some data to which the device responds.then i read from isnew.. .This where the program hangs.

时间: 作者:

InputStream is designed to block when you try and read data and none is available.you could call the available() method to see whether any data is available to read without blocking, but this only works one way - if available() returns non-zero you know you can read without blocking, but if it returns zero you won't necessarily be blocked.it is perfectly valid for an input stream to always return zero from available().

You may wish to look into the non-blocking I/O APIs of java.nio instead of using streams.

原作者:

You could handle each device in a separate thread.that way your program will stay responsive even when the devices aren't.but be aware of the pitfalls of multithreaded programming.

More information about multi-threaded programming in Java can be found on http://docs.oracle.com/javase/tutorial/essential/concurrency/

原作者:

How are you reading from the device?i'll assume you're using some form of FileInputStream to do it.that class looks to be suitable for reading from a filesystem to me, but a device, which could block for a long period of time is likely to lock up the Java thread until the device does respond.you need to make some kind of timed read request of the device, and i don't know of any Java class that does that.

Best suggestion i have is to write some JNI code that talks nicely and doesn't block when your devices stop responding.this is what i did when i was talking to a USB device.if i were coding this (for Linux) i would use select (which has a time period argument) to wait of an input from any of the devices.

原作者:
...