ClosedChannelException

时间:2013-03-14 11:32:19

标签: java

任何人都告诉我为什么我会在sc.connect

收到此例外

(sc = SocketChannel)

/**
 * Verify socket is connected.  If not currently connected will attempt to connect
 * @return true if already connected or connection successfully established
 */
private synchronized boolean verifyConnection() {
    if (sc.isConnected()) {
        return true;
    }
    try {
        if (!sc.isOpen()) {
            logger.info("Channel WebBroker->CC is CLOSED unexpectedly. Opening new channel " + getIpAddress() + ":" + getIpPort() + "");
            openChannel();
        }
        sc.socket().close();
        sc.connect(new InetSocketAddress(getIpAddress(), getIpPort()));
        while(!sc.finishConnect()){
            Thread.sleep(1);    
        }
        logger.info("Connection established " + getIpAddress() + ":" + getIpPort());
        sc.socket().setKeepAlive(true);
        return sc.isConnected();
    } catch (Exception e) {
        logger.info("failed to connect to " + getIpAddress() + ":" + getIpPort(), e);
        return false;
    }
}


private void openChannel() throws Exception {
    sc = SocketChannel.open();
    sc.socket().setKeepAlive(true);
    sc.socket().setSoTimeout(30000);
}

[错误]无法连接到10.201.1.53:8084

 java.nio.channels.ClosedChannelException: null
    at sun.nio.ch.SocketChannelImpl.ensureOpenAndUnconnected(SocketChannelImpl.java:472) ~[na:1.6.0_07]
    at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:486) ~[na:1.6.0_07]

编辑:最后我发现这是因为下面一行。

 sc.socket().close();

1 个答案:

答案 0 :(得分:0)

您无法重新连接套接字。你必须创建一个新的。

您还应注意isConnected()仅告诉您是否曾连接套接字。它不会告诉您整个连接的当前状态。类似地,isOpen()仅告诉您是否已经关闭它:不是对等方是否已经关闭它。您通常不能编写您尝试编写的方法。判断TCP连接是否仍然存在的唯一可靠方法是写入它。通常,检测是否有任何资源可用的唯一可靠方法是尝试使用它。不要试图预测未来。你仍然需要处理写入失败:为什么要写两次所有代码?