Checking for an available Object from Socket using

2019-09-01 06:43发布

问题:

When Server and Client are communicating using Strings (using BufferedReader and PrintWriter classes), the BufferedReader class has a method called ready(), meaning that there is a string waiting for the client to grab and process. This method also makes the server to be made with 2 threads, which is what I want to achieve.

When using ObjectInputStream and ObjectOutputStream classes, OIS class doesn't have a 'ready()' method, instead it has a method called 'available()' which returns the number of available bytes to be processed. The problem is that the available() method returns 0 every time and the lack of 'ready()' method in OIS makes the Server to be multi-threaded (1 thread for each connection plus main thread) and that's not what I want.

So, is there a way to check whether a Server has "received" an Object from the ObjectInputStream over the Socket without creating and holding a Thread for every connection?

回答1:

is there a way to check whether a Server has "received" an Object from the ObjectInputStream over the Socket without creating and holding a Thread for every connection?

No, because the server hasn't 'received an Object from the ObjectInputStream over the Socket'. It doesn't do that until you call readObject(). The reason ObjectInputStream.available() always returns zero is that it doesn't know in advance how large the next object is, so it can't tell whether it's all there or not, so it doesn't lie to you, it just says you probably can't read anything without blocking. There is no solution to this. Selector.select() isn't any more of a solution because it also doesn't know how large the next object is, not to mention the difficulty of switching between the non-blocking mode required for select() and the blocking mode required for readObject().

Use a dedicated read thread.