0

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?

Vitalij Kornijenko
  • 559
  • 1
  • 10
  • 22
  • 1
    If you don't want a thread-per-client ratio, use NIO, which uses a Selector to see if data is available or if a connection is available. You register the `Selector` to the socket. Then, you have 1 thread checking the selector for available keys. I have an example of how to setup a selector [here](http://stackoverflow.com/questions/24616774/non-socket-based-java-server/24617983#24617983) – Vince Nov 06 '14 at 00:10
  • @VinceEmigh that's nice. I'll need to take a look at some API but this definitely helps. Thank you. – Vitalij Kornijenko Nov 06 '14 at 00:17

1 Answers1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Or he could neglect `java.io` completely, and keep things non-blocking (if allowed; thats what my comment was suggesting). And couldn't object size can be accessable through a neat protocol?(serialize, send payload, send data) – Vince Nov 06 '14 at 00:54
  • @VinceEmigh He can't 'neglect `java.io` completely if he wants Serialization. – user207421 Nov 06 '14 at 01:07
  • And yes guys I do want Serialization. – Vitalij Kornijenko Nov 06 '14 at 13:37