I am working on socket programming and implementing custom request response protocol. For same I have used ObjectInputstream
and ObjectOutputstream
in java socket API.
The area where I have stucked is to check if data(in my case object) is available to read or not, for this I have tried to use the ObjectInputstream.available()
but it is returning 0 even if data is available on stream.
Why is it so?
So I have come up with solution: using exception and handling them in infinitely running loop, so even if exception(Read time out) occurs it will try to read again.
I have doubt is it good practice to do so? Or if any other solution you might have do suggest.
while (true){
try {
request = rpcClient.getRequest();
System.out.println(request);
// use threads to handle request for faster response(make use of request IDs)
rpcClient.sendResponse("test response");
} catch (SocketException e)
{// thrown when connection reset
System.out.println("Connection reset : Server is down.....");
break;
} catch (IOException e){
// thrown when read time out
System.out.println("read time out: listening again");
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
You shouldn't be using available()
in the first place. Disable the read timeout, so you can just let the thread wait until there's something to read (or the connection is broken).
I wouldn't recommend using ObjectStreams
for network communications though. It's not very suitable in most cases, considering the header information and other things that gets transferred. You're better off designing your own protocol to use and just send bytes over the network.