Link to home
Start Free TrialLog in
Avatar of BrindleFly
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 
Avatar of evijay
evijay

I didnt find any way to do this (as per my knowledge). The best way to handle this is

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(PushbackInputStream pInpStr) throws Exception
{
        int rd;
        try { rd  = pInpStr.read(); } catch (Exception e) { System.out.println("Socket closed !!"); return true; }
        System.out.println("not yet closed!!");
        pInpStr.unread(rd);
        return false;
}

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
ASKER CERTIFIED SOLUTION
Avatar of evijay
evijay

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial