This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
My requirement is to write a server that is capable of holding long conversations with the client based on socket programming for Java. I'm using ServerSocket to create TCP sockets. The problem I am running into is that I am not able to do [read, write, read] sequence of operations reliably on my socket. Here is my [read, write, read] code:
On line 5 in this code, the read operation is NOT blocking and will return -1. After some testing, I concluded that after flushing output [line 4], the input stream will not block anymore. However, if I comment out line 4, the read operation will block again, and will continue to block on subsequent attempts for read before any output flush. What I want is to implement persistent connections which enable me to read client's input, respond, and repeat without closing the socket.
Can anyone give me any ideas as to WHY this is the behaviour to be expected in my code? Why is that a output flush causes my input stream to behave unexpectedly?