Socket question

Here is some code for the thread/process to wait for input to arrive:

while ((input = in.readLine()) !=null)

{

//do stuff

}

I am trying to make it so I can see if the buffer has anything in it. If there is something there, read from it and do something. If the buffer is empty (received nothing from the socket) then stop and do something else.

Basically:

if (in.bufferEmpty() ==false)

{

//do something - socket has received data

}

else

{

//do something else, like, quit

}

I can't seem to do something like that. The input streams don't allow me (from what I can tell) to check on the internals of the buffer. So I have to write my own stream readers, etc, but I fanthom this is difficult to do.

Any help would be great. Thanks.

[1250 byte] By [dayrinnia] at [2007-10-3 4:34:36]
# 1
> if (in.bufferEmpty() == false)I think you don't need it at all.> while ((input = in.readLine()) != null)This should be enough and suffice, provided every line is canonically a 'line' which ends with a '\n' including blank lines.
hiwaa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 2

InputStream.available()

Having said that, there are few if any correct uses of this API. Every program I've ever seen that used it was better off just deleting it.

If you're using blocking I/O you're better off dedicating a thread to reading the socket and putting your other processing somewhere else.

ejpa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 3
> correct uses of this APICould you explain?
hiwaa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 4
I thought I just did.
ejpa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 5
> I thought I just did.You mean, in this thread?That is, using separate thread for socket I/O?Or, do you mean this Networking forum in general?
hiwaa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 6
Well of course I meant 'in this thread'.
ejpa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 7
Thanks, guru!
hiwaa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 8
If I use NIO will it allow me to do what I want? I am trying to avoid having 1 thread per socket.
dayrinnia at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...
# 9

Yes, NIO in non-blocking mode will do that, or InputStream.available(). The main objecttion to available() is that people often write code like this:

while (in.available() == 0)

{

Thread.sleep(2000);

}

int count = in.read(buffer);

// ...

In this code the while block is just literally a waste of time. If you have something constructive to do inside the block, such as polling another socket, by all means go ahead.

ejpa at 2007-7-14 22:38:16 > top of Java-index,Core,Core APIs...