使Java Server在一定时间后停止

时间:2017-07-28 14:43:55

标签: java server

我想创建一个在10秒后停止的Java Server程序。现在,我正在使用setSoTimeout方法。一旦时间到期,我将捕获异常并生成服务器结束消息。

但这似乎是一种解决方法。有没有更好的方法呢?

public class DailyAdviceServer
{
String[] adviceList = {"Take smaller bites", "Go for the tight jeans. No they do NOT make you look fat",
    "One word: inappropriate", "Just for today, be honest.  Tell your boss what you *really* think", 
    "You might want to rethink that haircut"};

public void startserver() {
    try {
        @SuppressWarnings("resource")
        ServerSocket serverSock = new ServerSocket(2727);
        serverSock.setSoTimeout(10000);
        while (true)
        {  
            Socket sock = serverSock.accept();
            OutputStreamWriter streamwriter = new OutputStreamWriter(sock.getOutputStream());
            BufferedWriter writer=new BufferedWriter(streamwriter);

            String advice = getAdvice();
            writer.write(advice);
            writer.close();
        }


    } catch (SocketTimeoutException ex)
    {
        System.out.println("The Server has now shut down.");
    }
     catch(IOException ex)
    {
         ex.printStackTrace(); 
    }
}

private String getAdvice() {
    int random = (int) (Math.random() * adviceList.length);
    return adviceList[random];
}

public static void main(String[] args)
{
    DailyAdviceServer server = new DailyAdviceServer();
    server.startserver();
}

}

1 个答案:

答案 0 :(得分:0)

您可以在创建ServerSocket后启动计时器,当计时器到期时您可以关闭它