有关Java中isClosed()和isConnected()的一些误解

    先说一个比较郁闷的事情,我一直以为Socket.isClose()和Socket.isConnected()是可以判断Socket是否连接的一个函数(这结论居然还是在CSDN上看到的,我就这么天真的相信了。),结果在一个项目上,我给学长指导的时候,告诉他这个地方是可以作为判断的。结果,他赤裸裸的躺枪了。我们可以看看JDK中是怎么说的:

/**
 * 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;
   }
}

    我们可以看到,这返回值只是一个boolean的变量,他并没有进行所谓的心跳,那么,这个closed变量又是在哪变修改的呢?

//注释就不贴出来了
public synchronized void close() throws IOException {
   synchronized(closeLock) {
       if (isClosed())
           return;
       if (created)
           impl.close();
       closed = true;
    }
}

    我们可以看到,除非你手动的close掉这个Socket连接,不然closed就一直处在false的初始量。所以,这个isClosed()方法并不能作为判断Socket是否还活着的依据,那么isConnected呢。

/**
 * Returns the connection state of the socket.
 * <p>
 * Note: Closing a socket doesn't clear its connection state, which means
 * this method will return 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;
}

    我们可以仅从注释中看到:@return true if the socket was successfuly connected to a server.也就是说,这个返回值只是一个状态量,只是说明了这个Socket有没有成功的连接过,而并不是说现在有没有连接上。

    综上所述,以下代码是没有一点意义的,在判断Socket是否连接的时候。各位慎重啊。不要再掉坑里了。。。。

if(Socket.isClosed && Socket.isConnected()){
    //Socket是连接的
}

 

4 Replies to “有关Java中isClosed()和isConnected()的一些误解”

Leave a Reply

Your email address will not be published. Required fields are marked *