Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java多线程服务器*有时*在ServerSocket.accept()方法中抛出SocketException(套接字关闭)_Java_Multithreading_Exception - Fatal编程技术网

Java多线程服务器*有时*在ServerSocket.accept()方法中抛出SocketException(套接字关闭)

Java多线程服务器*有时*在ServerSocket.accept()方法中抛出SocketException(套接字关闭),java,multithreading,exception,Java,Multithreading,Exception,我已经研究这个问题好几个小时了,但我无法找到一个合适的解决方案或解释为什么会抛出这个异常(java.net.SocketException:socketclosed)。我的最后一个方法是问你们 我为测试目的创建了一个简单的服务器客户端应用程序(“真实”应用程序使用相同的逻辑),请参见下文 如果我重复调用同一个测试用例(例如通过TestNG的invocationcount注释参数或使用简单的for循环),在某个点上会出现java.net.SocketException:socketclosed 下

我已经研究这个问题好几个小时了,但我无法找到一个合适的解决方案或解释为什么会抛出这个异常(java.net.SocketException:socketclosed)。我的最后一个方法是问你们

我为测试目的创建了一个简单的服务器客户端应用程序(“真实”应用程序使用相同的逻辑),请参见下文

如果我重复调用同一个测试用例(例如通过TestNG的invocationcount注释参数或使用简单的for循环),在某个点上会出现java.net.SocketException:socketclosed

下面的测试用例基本上只是启动服务器(打开服务器套接字),等待几毫秒,然后再次关闭套接字。关闭服务器套接字需要打开一个套接字,以便服务器从ServerSocket.accept()方法返回(请参阅server#shutdown()

我认为这可能是ServerSocket.accept()行后面的代码的多线程问题。所以我暂时用一个同步块来包围它——也没用

你知道为什么会抛出这个异常吗

最好的, 克里斯

Server.java如下所示:

package multithreading;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;

public class Server {

private ServerSocket serverSocket;
private boolean isShuttingDown;
private final static Logger logger = Logger.getLogger(Server.class);

public void start() throws Exception {
    try {
        serverSocket = new ServerSocket(5000);
        isShuttingDown = false;
    } catch (Exception e) {
        throw new RuntimeException("Starting up the server failed - aborting", e);
    }

    while (true) {
        try {
            Socket socket = serverSocket.accept();

            if (!isShuttingDown) {
                new Thread(new EchoRequestHandler(socket)).start();
            } else {
                logger.info("Server is going to shutdown");
                break;
            }
        } catch (IOException e) {
            logger.error("Error occured while waiting for new connections, stopping server", e);
            throw e;
        }
    }
}

public synchronized boolean isRunning() {
    if (serverSocket != null && serverSocket.isBound() && !serverSocket.isClosed() && !isShuttingDown) {
        return true;
    }
    return false;
}

public synchronized void shutdown() throws IOException {
    if (isRunning()) {
        isShuttingDown = true;
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                /*
                 * since the server socket is still waiting in it's accept()
                 * method, just closing the server socket would cause an
                 * exception to be thrown. By quickly opening a socket
                 * (connection) to the server socket and immediately closing
                 * it again, the server socket's accept method will return
                 * and since the isShuttingDown flag is then false, the
                 * socket will be closed.
                 */
                new Socket(serverSocket.getInetAddress(), serverSocket.getLocalPort()).close();

                serverSocket.close();
            } catch (IOException e) {
                logger.error("Closing the server socket has failed - aborting now.", e);
                throw e;
            }
        }
    } else {
        throw new IOException("Server socket is already closed which should not be the case.");
    }
}
}
测试类执行以下操作:

package multithreading;

import java.io.IOException;

import org.testng.annotations.Test;

public class Testing {

// @Test(invocationCount=10, skipFailedInvocations=true)
@Test
public void loadTest() throws InterruptedException, IOException {
    for (int i = 0; i < 10; i++) {
        final Server s = new Server();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    s.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }).start();
        Thread.sleep(500);
        gracefullyShutdownServer(s);
        Thread.sleep(1000);
    }
}

private void gracefullyShutdownServer(final Server server) throws InterruptedException {
    try {
        server.shutdown();
        while (server.isRunning()) {
            Thread.sleep(500);
        }
    } catch (IOException e) {
        System.err.println(e);
    }
}

}

如本链接中所述,打开一个插座以关闭另一个插座是错误的。在套接字上调用close应该通过抛出一个可以安全捕获和忽略的异常来取消“接受”。

J.N.关于处理关闭的方式是正确的

至于这不起作用的原因,我认为竞争在于您的服务器代码读取
isShuttingDown
时没有同步。我不明白为什么值更改应该立即对服务器线程可见。所以很有可能再进行一轮

正如J.N.所说:在接受时处理服务器中的异常。如果您想知道您的代码在套接字上执行
close
操作是否可能引发异常,请将
isShuttingDown
放在周围,确保安全访问它。(一个
synchronized(这个){}
块,或者编写一个非常短的同步访问器。)


在这个特定的例子中,我认为使
isShuttingDown
volatile就足够了,这在developerWorks文章中有详细介绍。但是要小心,这不是一个灵丹妙药。

提供困扰您的异常的堆栈跟踪会很好。@Mat:刚刚添加了堆栈跟踪(很抱歉没有首先发布它,我真蠢)给出的链接不再有效,不过感谢您提供的信息:)
ERROR 2011-03-13 16:14:23,537 [Thread-6] multithreading.Server: Error occured while waiting for new connections, stopping server
java.net.SocketException: Socket closed
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:390)
at java.net.ServerSocket.implAccept(ServerSocket.java:453)
at java.net.ServerSocket.accept(ServerSocket.java:421)
at multithreading.Server.start(Server.java:26)
at multithreading.Testing$1.run(Testing.java:18)
at java.lang.Thread.run(Thread.java:680)
java.net.SocketException: Socket closed
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:390)
at java.net.ServerSocket.implAccept(ServerSocket.java:453)
at java.net.ServerSocket.accept(ServerSocket.java:421)
at multithreading.Server.start(Server.java:26)
at multithreading.Testing$1.run(Testing.java:18)
at java.lang.Thread.run(Thread.java:680)