可以引起网络连接关闭的情况有以下4种:
直接调用Socket类的close方法。
只要Socket类的InputStream和OutputStream有一个关闭,网络连接自动关闭(必须通过调用InputStream和OutputStream的 close方法关闭流,才能使网络可爱接自动关闭)。
在程序退出时网络连接自动关闭。
将Socket对象设为null或未关闭最使用new Socket(…)建立新对象后,由JVM的垃圾回收器回收为Socket对象分配的内存空间后自动关闭网络连接。
虽然这4种方法都可以达到同样的目的,但一个健壮的网络程序最好使用第1种或第2种方法关闭网络连接。这是因为第3种和第4种方法一般并不会马上关闭网络连接,如果是这样的话,对于某些应用程序,将会遗留大量无用的网络连接,这些网络连接会占用大量的系统资源。
isClose:
isclose 用来返回当前socket是否关闭,关闭返回true。也就是说,不管Socket对象是否曾经连接成功过,只要处于关闭状态,isClosde就返回true。如果只是建立一个未连接的Socket对象,isClose也同样返回true。
/**
* Returns the closed state of the socket.
*
* @return true if the socket has been closed
* @since 1.4
* @see #close
*/
public boolean isClosed() {
synchronized(closeLock) {
return closed;
}
}
isConnected():
isConnected() 用于返回socket曾经是否成功连接过,而不是当前状态。isConnected方法所判断的并不是Socket对象的当前连接状态,而是Socket对象是否曾经连接成功过,如果成功连接过,即使现在isClose返回true,isConnected仍然返回true。
/**
* Returns the connection state of the socket.
* <p>
* Note: Closing a socket doesn't clear its connection state, which means
* this method will return {@code true} for a closed socket
* (see {@link #isClosed()}) if it was successfuly connected prior
* to being closed.
*
* @return true if the socket was successfuly connected to a server
* @since 1.4
*/
public boolean isConnected() {
// Before 1.3 Sockets were always connected during creation
return connected || oldImpl;
}
因此,要判断当前的Socket对象是否处于连接状态,必须同时使用isClose和isConnected方法,即只有当isClose返回false,isConnected返回true的时候Socket对象才处于连接状态。