Basically you want a non-blocking read... join the club.

Here's _a_ solution: use two threads. The first thread reads the data,
the second thread sleeps for a while and wakes up the first thread if
it hasn't read yet. (yeah, "ugh" was my first reaction to this method
too....)

Here's _a_better_ solution (but still not optimal):

byte[]
readUpToNBytesWithOutBlockingForever(
  InputStream from,
  int N,
  int maxLoops) {
    byte[] retval = new Byte[N];
    int temp;
    int rsf = 0;
    int lcv = 0;
    while (rsf < N && 0 < lcv) {
      temp = from.available();
      if (temp > 0) {
        from.read(retval, rsf, temp); //won't block
        lcv = 0; //reset loop count var
        rsf += temp;
      } else {
        ++lcv;
        //you could also do a thread.sleep() here if your device is
        // really slow, or some form of thread.yeild() if you are
        // worried about chewing up CPU time in a busy wait state
    }
    if (rsf = N)
      return retval;
    else
      ...
  }

Well, it's ugly code, but you get the idea....

Now I'm curious... what file are you using to talk to a serial device?
something in /dev, but which? /dev/cua? does this work both for read
and write? I'm looking at doing some form of out-of-band signaling
between two PCs (right next to each other) and a null modem cable sounds
a lot cheaper than my other ideas.... ;) 

Oh... but wait... does available() correctly report on these "files"
or do they suffer the same problem as those in /proc?  It would be nice,
in this case, if available() would report the bytes as yet unconsumed
for the port or pipe or whatever is under the file. Of course that assumes
there is a buffering under there... and now I'm getting into deeper water
than I care to swim this week... any kernel hackers care to step in and
tell me I'm being a wishfull fool? :) -=Chris

At 04:25 AM 2/15/99 PST, Ejaz Mohd wrote:
>Hello,
>I've small problem. 
>I've a device connected on a serial port. To communciate with that 
>device I've opened random access file.
>This strategy works but when device is unable to send me the
>required bytes or when device is switched off my java program
>goes in an blocked mode. And unless I press ^C the program does'nt
>come out.
>One of the alternatives is to use 'Communication API' but is their
>any other method?
>Ejaz
>
>______________________________________________________
>Get Your Private, Free Email at http://www.hotmail.com
>
>
>

<*> cabbey at rconnect dot com  http://homepage.rconnect.com/cabbey/ <*>
"What can Microsoft do? They certainly can't program around us." - Linus

-----BEGIN GEEK CODE BLOCK-----   Version:3.12   http://www.geekcode.com
GCS$/IT/PA$ d(-) s++:+ a-- C+++$ UL++++ UA++$ P++ L++ E- W++ N+ o? K? !P
w---(+)$ O- M-- V-- Y+ PGP+ t--- 5++ X+ R tv b+ DI+++ D G e++ h(+) r@ y?
------END GEEK CODE BLOCK------

Reply via email to