0
10秒後に停止するJava Serverプログラムを作成したいと思います。今はsetSoTimeoutメソッドを使用しています。時間が経過すると、私は例外をキャッチし、サーバー終了メッセージを生成します。一定時間後にJavaサーバーを停止させる
しかし、これは回避策のようです。それを行うより良い方法はありますか?
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();
}
}