我一直在研究这个问题几个小时和几个小时,我无法提出一个体面的解决方案或解释为什么这个异常(java.net.SocketException:Socket关闭)被抛出。我的最后一种方法是现在问你们。
我已经为测试目的创建了一个简单的服务器 - 客户端应用程序(“真正的”应用程序使用相同的逻辑),见下文。
如果我重复调用相同的测试用例(例如通过TestNG的 invocationcount 注释参数或使用简单的for循环),在某些时候会有 java.net.SocketException:Socket关闭 。
下面的测试用例基本上只是启动服务器(打开服务器套接字),等待几毫秒然后再次关闭套接字。关闭服务器套接字涉及打开套接字,以便服务器从ServerSocket.accept()方法返回(参见Server#shutdown())。
我虽然在ServerSocket.accept()行之后可能是代码的多线程问题。所以我用一个synchronized块暂时包围它 - 也没有帮助。
你知道为什么会抛出这个异常吗?
最佳, 克里斯
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)
答案 0 :(得分:5)
J.N。关于你应该处理关闭的方式是正确的。
至于为什么这不起作用,我认为竞争是你的服务器代码在没有同步的情况下读取isShuttingDown
。我不明白为什么值更改应该立即显示给服务器线程。所以它可能会进行另一轮。
所以J.N.说:接受时处理服务器中的异常。如果您想知道代码在套接字上执行close
是否可能,请确保isShuttingDown
周围安全地访问它。 (可以是synchronized (this) {}
块,也可以写一个非常短的同步访问器。)
在这个特定情况下,我认为制作isShuttingDown
volatile 就足够了,详见developerWorks文章Java theory and practice: Managing volatility。但要小心,这不是一个神奇的子弹。
答案 1 :(得分:4)
正如此javadoc链接中所指定的,打开套接字以关闭另一个套接字是错误的。在你的套接字上调用close应该通过抛出你可以捕获并安全忽略的异常来取消“接受”。