gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:01:46 25 4
gpt4 key购买 nike

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

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

如果我重复调用相同的测试用例(例如通过 TestNG 的 invocationcount 注释参数或通过使用简单的 for 循环),在某些时候会有一个 java.net.SocketException:套接字已关闭

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

我认为这可能是 ServerSocket.accept() 行之后的代码的多线程问题。所以我暂时用同步块(synchronized block)包围它 - 也没有帮助。

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

最好的,克里斯

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);
}
}

}

堆栈跟踪如下所示:

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)

最佳答案

J.N.关于您应该处理关闭的方式是正确的。

至于为什么这不起作用,我认为竞争是您的服务器代码在没有同步的情况下读取 isShuttingDown。我不明白为什么服务器线程应该立即看到值更改。所以它很可能会进行另一轮。

所以 J.N.说:接受时处理服务器中的异常。如果您想知道异常是否可能是由您的代码在套接字上执行close引起的,请保持您的isShuttingDown,确保您安全地访问它。 (synchronized (this){} block ,或者编写一个非常短的同步访问器。)

在这种特定情况下,我认为制作 isShuttingDown volatile 就足够了,详见这篇 developerWorks 文章 Java theory and practice: Managing volatility .但要小心,这不是 Elixir 。

关于Java 多线程服务器 *有时* 在 ServerSocket.accept() 方法中抛出 SocketException(套接字关闭),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5282104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com