1

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.

3 Answers3

0

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.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
0

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/

Philipp
  • 67,764
  • 9
  • 118
  • 153
  • Multithreading may not be workable in my case as the Ethernet device connected to serial devices allows 2 connections at a time as well as Once I have data from all 5 devices I push it in database – user2454556 Jun 19 '13 at 12:30
0

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.

Dobbo
  • 1,188
  • 3
  • 16
  • 27