I am writing a socket-based server in java. A client connects to it(a web-browser) and the server sends back a simple html code and sets cookie to recognize next time client connects to it again. I am using PrintStream to write to the socket , but flush is not working. The only way i can flush is to use shutdownoutput or close and both close the socket stream. But i do not want that because i am readin/writing to it several times in several places in the code. What can do? Could't get any help from the tags. I also tried other buffered writer classes, same problem.
Asked
Active
Viewed 9,884 times
2
-
Can you post an example of your server code? – Kylar Feb 14 '10 at 04:33
-
2This is really old but for posterity, `ps.flush()` is unnecessary because a flush happens when `"\n"` is printed -- i.e. `println()` is called. In addition, in `SocketOutputStream` the `flush()` method is a no-op anyway. – Gray Nov 25 '11 at 14:04
-
Are you setting the `Content-Length` header? Code please. – user207421 Aug 23 '23 at 08:12
2 Answers
3
Ah yeah , sillyproblem , you just have to use pstream.writeln(""); since breader.readLine() reads until it finds '\n' character. so write() won't work.

Elias
- 39
- 1
0
I would try calling this method instead of flush:
public boolean checkError()
Returns:
True if and only if this stream has encountered an IOException other than InterruptedIOException, or the setError method has been invoked
See if it is failing for some reason to do the flush (checkError calls flush internally and remembers error state).
Also worth trying is connecting to the server using telnet and seeing if the data is being returning immediately, or writing a simple java client socket program to check (cut/paste one off the net).
It might be that the browser has decided to deliberately wait for more input before displaying your html (especially if the html is not perfectly formed). I seem to remember having this issue myself in the past.

DaveC
- 2,020
- 15
- 13