I'm writing a simple tcp stream SMTP server. I wrote following code to check if the client connection is still available. Simply peeking one byte to see if socket input stream is working. But when I set in.mark(x)
read ahead limit to 1, it shows error when I attempt to send Header for the second time. When it's set to 2, it doesn't seem to have any problem at all. Why is this?
// check if client disconnected
try {
in.mark(1); // 1 char read ahead limit
if (in.read() == -1) {
System.out.println("CONNECTION CLOSED BY CLIENT!");
return; // end of thread
} else {
in.reset();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
The error I get is this:
java.io.IOException: Mark invalid
at java.io.BufferedReader.reset(BufferedReader.java:512)
at smtp.server.SocketThread.run(SocketThread.java:59)
The entire code is on my github.
Forget it. Just read and write, and deal with the exceptions as they arise.
At present you are engaged in fortune-telling. Even if you find a method that works to tell you whether the client connection is alive now, it could go down between calling this method and the very next line of code.
The only method that actually works of trying to detect whether a resource is available is to try to use it in the normal way.