我正在运行一个服务器并生成多个线程以允许多个套接字。显然,我希望能够在命令中关闭所有套接字。我为我的服务器编写了一个启动和停止功能,除非我在Windows上运行它,否则它会立即工作。
开始/停止
public void startServer(int port, int maxThreads, int timeout) throws IOException {
fileServer = new ServerSocket();
fileServer.setPerformancePreferences(1, 0, 1);
fileServer.bind(new InetSocketAddress(port));
for (int threads = 0; threads < maxThreads; threads++) {
sockets.add(new Thread(new ServerInit(fileServer, timeout)));
System.out.println("Socket " + threads + " initialized...");
}
for (int socket = 0; socket < sockets.size(); socket++) {
(sockets.get(socket)).start();
System.out.println("Socket " + socket + " started!");
}
}
public void stopServer() {
if (fileServer.isBound()) {
for (int thread = 0; thread < sockets.size(); thread++) {
sockets.get(thread).interrupt();
}
for (int thread = 0; thread < sockets.size(); thread++) {
try {
sockets.get(thread).join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ServerInit
class ServerInit implements Runnable {
private ServerSocket server;
private int timeout;
public void run() {
while (!Thread.interrupted()) {
try {
server.setSoTimeout(1000);
Socket client = server.accept();
client.setSoTimeout(timeout);
processRequest(receiveRequest(client), client);
client.close();
} catch (SocketTimeoutException ste) {
} catch (IOException io) {
io.printStackTrace();
}
}
System.out.println("Socket closed");
}
}
问题是由于阻塞超时,每个线程单独停止一秒钟,但是,这仅在Windows上发生。为什么Windows表现得如此不同?我该如何解决这个问题?
修改
每个套接字都有一秒超时。我意识到通过这样做会导致每个套接字花费一秒钟超时并因此关闭,但是为什么Windows为每个连接线程花费一秒钟而不是花费一秒总数?