BrindleFly
asked on
closing a socket
I have a very basic question: how can I test a Socket to determine whether or not it is open?
I know I receive an exception if the socket is unexpectedly closed. I also know I receive a known return code (e.g. null) if I read or write to a closed socket. But how do I ask a Socket whether or not it is open without having to read or write?
Thanks!
Joe
I know I receive an exception if the socket is unexpectedly closed. I also know I receive a known return code (e.g. null) if I read or write to a closed socket. But how do I ask a Socket whether or not it is open without having to read or write?
Thanks!
Joe
Do you mean to test if a socket is still valid?
eg.
// start
Socket mysocket = new Socket(hostname,portnum);
// Test if socket is valid
if(mysocket = null) {
// socket closed, do something
} else {
// socket open, read or write using socket
}
// end
eg.
// start
Socket mysocket = new Socket(hostname,portnum);
// Test if socket is valid
if(mysocket = null) {
// socket closed, do something
} else {
// socket open, read or write using socket
}
// end
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
After you say
InputStream is = socket.getInputStream();
create a push back input stream
PushbackInputStream ps = new PushBackInputStream (ps);
use ps instead of is to read data from socket.
Write an utility routine to test for socket closure as below
public static boolean isSocketClosed(PushbackInp
{
int rd;
try { rd = pInpStr.read(); } catch (Exception e) { System.out.println("Socket
System.out.println("not yet closed!!");
pInpStr.unread(rd);
return false;
}