サーバーとクライアントのプログラミングにOracleのKnockKnockの例を使用しています。これにより、クライアントがサーバーに接続すると、KnockKnockジョークを受信して対話します。すべてが順調に進んでいます。
私の質問は、クライアントが完了してサーバーから切断されると、サーバープログラムも終了することです。サーバーが終了した場合、サーバー側を手動で再起動せずに別のクライアントの要求を受け入れることができるように、サーバーを再度自動実行するにはどうすればよいですか?
以下は私のコードで、コメントは私が立ち往生している場所を示しています。vmwareプレーヤーで実行されている2つのcentosvmを使用しています。
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
server();
/*HERE IS WHERE I AM STUCK
* If I call server() above in my main method everything runs great.
* However, I would like to put a timer or something inside main so that
* every second it checks to see if server() is still running and if not
* then start it up again.
*/
}
public static void server() throws IOException{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}