如何自动关闭Java服务器?
我需要一种方法来自动关闭服务器程序,该程序使用某种计时器运行。到现在为止,这就是我得到的如何自动关闭Java服务器?,java,timer,client-server,session-timeout,Java,Timer,Client Server,Session Timeout,我需要一种方法来自动关闭服务器程序,该程序使用某种计时器运行。到现在为止,这就是我得到的 long start = System.currentTimeMillis(); long end = start + 10 * 1000; // 60 seconds * 1000 ms/sec while (System.currentTimeMillis() < end) { Socket connectionSocket = welcomeSocket
long start = System.currentTimeMillis();
long end = start + 10 * 1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(
connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
count = count + 1;
}
welcomeSocket.close();
long start=System.currentTimeMillis();
长端=起点+10*1000;//60秒*1000毫秒/秒
while(System.currentTimeMillis()
这可能吗?请帮忙,不要否决投票。关于Java中的客户机-服务器,我有点不了解。我不确定您是否同意
线程。我还是会建议你去看看这门课
您可以创建一个计时器
,它创建了一个线程来关闭服务器。您可以将连接设为最终变量
,然后在计时器
线程启动后,使用同步
访问将其关闭。运行线程中的代码(在下面的代码中命名为服务器),然后启动另一个这样的线程,以便在您想要退出时进行中断:
Thread server = {the one you have};
Thread timeout = new Thread() {
public void run() {
long end = start + 10 * 1000;
try {
Thread.sleep(end);
} catch (InterruptedException e) {
//handle this
}
server.interrupt();
}
}
timeout.start();
accept现在将抛出InterruptedException并绕过所有其他代码 你可以用它
通常,您将使用一些值(如100ms)设置该值,输入一个循环并调用accept。当抛出超时异常时,您将检查是否可以退出,或者退出循环,或者继续
然后确保完成后清洁插座