I want to know if there are available bytes to be read in a Java NIO Socket. In C/C++ it can be done using something like this:
int available(int fd){
long readable = 0;
if (ioctl(fd, FIONREAD, &readable) < 0){
// error
}
return (int) readable;
}
It is possible to do the same operation with Java NIO (using SocketChannel, Selector, Socket, etc.)?
The idea behind NIO is to provide a way to wait for events (e.g. “connection has readable data ready”) from any one of multiple connections at the same time, which sounds like exactly what you are looking for. Take a look at
java.nio.channels.Selector. You basically register the “readable” event of all the connections you have with this selector object and then call one of threeselectmethods that will wait for an event on one of your connections:select()– blocks until an event is available (use if your program has nothing else to do)select(long timeout)– blocks until an event is available or a timeout happens (use if you want to conserve CPU load and increase network responsiveness if it’s OK if your program slows down a bit)selectNow()– returns immediately (use if your program needs to keep running)Then you use the
selectedKeysmethod to grab a list of all connections that have an event waiting (for example, have data ready to be read). Then just iterate over this list and read from the connections with data only and ignore the other connections that aren’t in the list as they have no data available.This will allow you to check without blocking WHETHER data is available (is connection in the list or not), but not HOW MUCH data is available. But if you then do a read on the connection with data available, it will return immediately without blocking and return as much data as is available, if you’ve given it a big enough buffer. You can then choose to buffer this data somewhere and make the amount of data in the buffer available, but something tells me you don’t really need this anyways and just want to go ahead and process the data.