0

任何人都告诉我为什么我会在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();
4

1 回答 1

0

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

您还应该注意 isConnected() 只告诉您是否曾经连接过套接字。它不会告诉您整个连接的当前状态。同样 isOpen() 只告诉你是否已经关闭它:而不是对等方是否已经这样做了。您通常无法编写您尝试编写的方法。判断 TCP 连接是否仍然存在的唯一可靠方法是对其进行写入。通常,检测任何资源是否可用的唯一可靠方法是尝试使用它。不要试图预测未来。无论如何,您仍然必须处理写入失败:为什么要编写所有代码两次?

于 2013-03-14T21:49:18.983 回答